我正在尝试解析如下所示的数组:
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>";
}
将子数组移出主数组并循环遍历它:
$sub = array_shift($my_arr);
foreach ($sub as $row) {
echo $row['Titel'], "<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>";
}
使用 current
ref : http://in3.php.net/manual/en/function.current.php
$a = current($my_arr);
foreach($a as $row){
echo "i found one <br>";
}