0

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

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

4

4 回答 4

2

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

$a = reset($my_arr);
foreach($a as $row){
    echo "i found one <br>";
}
于 2013-01-24T04:06:23.440 回答
0

您正在尝试做的是 object,而不是 array $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>";
}   
于 2013-01-24T04:09:28.633 回答
0

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

$a = current($my_arr);
foreach($a as $row){
    echo "i found one <br>";
}
于 2013-01-24T04:39:08.100 回答
0

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

$sub = array_shift($my_arr);
foreach ($sub as $row) {
    echo $row['Titel'], "<br>";
}
于 2013-01-24T04:12:39.333 回答