PHP循环遍历整个多维数组,但只返回一个结果

问题描述:

I have got an multidimensional array on which I run a foreach loop.

I basically want to see if I've got the country_url stored in an database. If it is in the database then I'll echo "exists" but if it doesn't then I want to echo "doesn't exist". I don't want it to tell me for each array if it exists or not, but I want the foreach loop to tell me whether the country_url exists in one of the arrays or not.

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

Would anyone be able to help me out with this?

我有一个多维数组,我在其上运行一个foreach循环。 p>

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

   foreach($ countriesForContinent as $ country){
 if($ country ['country_url'] == $ country_url){
 echo“exists”; 
} else {
 echo“不存在”  ; 
} 
} 
  code>  pre> 
 
 

有人能帮我解决这个问题吗? p> div>

Try this:

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

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

You could store a variable and then use break to terminate the loop once the item is found:

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

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

This should work:

$text = "doesn't exist";

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

echo $text;

As an alternative to the other answers, you could do the following:-

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

This is probably slightless less efficient though as it will essentially loop through all $countriesForContinent rather than finding a match and break[ing].