【问题标题】:PHP Looping through entire multidimensional array but only giving one result backPHP循环遍历整个多维数组但只返回一个结果
【发布时间】:2013-04-30 13:52:09
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: php loops foreach


    【解决方案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";
    }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        这应该可行:

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

        【讨论】:

          【解决方案4】:

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

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

          这可能效率稍低一些,因为它基本上会循环遍历所有$countriesForContinent,而不是找到匹配项和break[ing]。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-04-21
            • 2011-01-02
            • 2016-02-16
            • 2021-09-17
            • 1970-01-01
            相关资源
            最近更新 更多