Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP在整个多维数组中循环,但只返回一个结果_Php_Loops_Foreach - Fatal编程技术网

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

PHP在整个多维数组中循环,但只返回一个结果,php,loops,foreach,Php,Loops,Foreach,我有一个多维数组,我在上面运行foreach循环 我基本上是想看看我是否把国家的url存储在数据库中。如果它在数据库中,那么我将回显“存在”,但如果它不存在,那么我想回显“不存在”。我不希望它告诉我每个数组是否存在,但我希望foreach循环告诉我country\u url是否存在于其中一个数组中 foreach ($countriesForContinent as $country) { if ($country['country_url']==$country_url) {

我有一个多维数组,我在上面运行foreach循环

我基本上是想看看我是否把国家的url存储在数据库中。如果它在数据库中,那么我将回显“存在”,但如果它不存在,那么我想回显“不存在”。我不希望它告诉我每个数组是否存在,但我希望foreach循环告诉我country\u url是否存在于其中一个数组中

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

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

您可以存储一个变量,然后使用
break
在找到项目后终止循环:

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

if ($exists) {
  echo "Success!";
}
试试这个:

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

if ($exist){
   echo "exists";
} else {
   echo "doesn't exist";
}
这应该起作用:

$text = "doesn't exist";

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

echo $text;

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

echo (in_array($country_url, array_map(function($v) { return $v['country_url']; }, $countriesForContinent))) ? 'exists' : 'does not exist';
这可能会稍微降低效率,因为它基本上会在所有
$countriesforcontaint
中循环,而不是找到匹配项并
中断
[ing]