2013-04-30 81 views
0

我有一个多维数组,我运行一个foreach循环。PHP循环遍历多维数组,但只给出一个结果

我基本上想看看我是否已将country_url存储在数据库中。如果它在数据库中,那么我会回显“存在”,但如果它不存在,那么我想回显“不存在”。我不希望它告诉我每个数组是否存在,但我希望foreach循环告诉我country_url是否存在于其中一个数组中。

foreach ($countriesForContinent as $country) { 
    if ($country['country_url']==$country_url) { 
     echo "exists"; 
    } else { 
     echo "doesn't exist"; 
    } 
} 

任何人都可以帮助我吗?

回答

1

试试这个:

$exist = false;  
foreach ($countriesForContinent as $country) { 
     if ($country['country_url']==$country_url) { 
      $exist = true; 
      break; 
     } 
    } 

if ($exist){ 
    echo "exists"; 
} else { 
    echo "doesn't exist"; 
} 
1

你可以存储一个变量,然后使用break终止循环一旦该项目被发现:

$exists = false; 
foreach ($countriesForContinent as $country) { 
    if ($country['country_url']==$country_url) { 
    $exists = true; 
    break; 
    } 
} 

if ($exists) { 
    echo "Success!"; 
} 
0

这应该工作:

$text = "doesn't exist"; 

foreach ($countriesForContinent as $country) { 
    if ($country['country_url']==$country_url) { 
     $text = "exists"; 
     break; 
    } 
} 

echo $text; 
0

作为其他答案的替代方案,您可以执行以下操作: -

echo (in_array($country_url, array_map(function($v) { return $v['country_url']; }, $countriesForContinent))) ? 'exists' : 'does not exist'; 

这可能是slightless效率较低,虽然,因为它会通过所有$countriesForContinent基本循环,而不是找到匹配和break [和]。