繁体   English   中英

数组中的PHP foreach子数组

[英]PHP foreach subarray in array

我正在尝试解析一个看起来像这样的数组:

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的新手,这似乎是正确的方法。 显然不是。 有人可以帮我吗?

使用reset可以获取$my_arr的第一个元素,而无需知道键名:

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

您尝试做的是对象,而不是数组$my_arr->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>";
}   

将子阵列移离主阵列并在其上循环:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM