【问题标题】:PHP foreach subarray in arrayPHP foreach 数组中的子数组
【发布时间】:2013-01-24 04:02:14
【问题描述】:

我正在尝试解析一个如下所示的数组:

array(1) {
  ["StrategischeDoelstellingenPerDepartement"] => array(412) {
    [0] => array(5) {
      ["CodeDepartement"] => string(8) "DEPBRAND"
      ["NummerHoofdstrategischeDoelstelling"] => string(1) "1"
      ["Nummer"] => string(2) "27"
      ["Titel"] => string(22) "DSD 01 - HULPVERLENING"
      ["IdBudgetronde"] => string(1) "2"
    }
    [1] => array(5) {
      ["CodeDepartement"] => string(8) "DEPBRAND"
      ["NummerHoofdstrategischeDoelstelling"] => string(1) "2"
      ["Nummer"] => string(2) "28"
      ["Titel"] => string(24) "DSD 02 - Dienstverlening"
      ["IdBudgetronde"] => string(1) "2"
    }
    [2] => array(5) {
      ["CodeDepartement"] => string(8) "DEPBRAND"
      ["NummerHoofdstrategischeDoelstelling"] => string(1) "2"
      ["Nummer"] => string(2) "29"
      ["Titel"] => string(16) "DSD 03 - KLANTEN"
      ["IdBudgetronde"] => string(1) "2"
    }
    ...

(数组继续,但它太大,无法在此处完整发布)

我可以像这样在数组上做一个 foreach 循环:

foreach($my_arr->StrategischeDoelstellingenPerDepartement as $row){
    echo "i found one <br>";
}

但是,我想在其他数组上做同样的事情,我想让函数通用。第一个键(在这种情况下为StrategischeDoelstellingenPerDepartement)有时会发生变化,这就是我想通用的原因。我已经尝试了以下方法:

foreach($my_arr[0] as $row){
    echo "i found one <br>";
}

但随后我收到以下通知,但没有数据:

Notice: Undefined offset: 0 in C:\Users\Thomas\Documents\GitHub\Backstage\application\controllers\AdminController.php on line 29

这可能是一个愚蠢的问题,但我是 PHP 新手,这似乎是正确的方法。显然,它不是。谁能帮帮我好吗?

【问题讨论】:

    标签: php zend-framework


    【解决方案1】:

    在不知道键名的情况下使用reset获取$my_arr的第一个元素:

    $a = reset($my_arr);
    foreach($a as $row){
        echo "i found one <br>";
    }
    

    【讨论】:

      【解决方案2】:

      将子数组移出主数组并循环遍历它:

      $sub = array_shift($my_arr);
      foreach ($sub as $row) {
          echo $row['Titel'], "<br>";
      }
      

      【讨论】:

        【解决方案3】:

        你试图做的是对象,而不是数组$my_arr-&gt;StrategischeDoelstellingenPerDepartement。 您可以使用isset() 来检查索引是否存在:

        if(isset($my_arr['StrategischeDoelstellingenPerDepartement'])){
            foreach($my_arr['StrategischeDoelstellingenPerDepartement'] as $row){
                echo "i found one <br>";
            }
        }
        

        或者,您可以使用array_values() 忽略数组键并使其成为索引数组:

        $my_new_arr = array_values($my_arr);
        foreach($my_new_arr as $row){
            echo "i found one <br>";
        }   
        

        【讨论】:

          【解决方案4】:

          使用current 参考:http://in3.php.net/manual/en/function.current.php

          $a = current($my_arr);
          foreach($a as $row){
              echo "i found one <br>";
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-09-11
            • 2017-03-05
            • 2013-07-31
            • 1970-01-01
            • 2010-11-13
            • 2016-09-08
            • 1970-01-01
            相关资源
            最近更新 更多