如何调用多维数组中的数组ID?

时间:2013-10-17 19:18:59

标签: php arrays multidimensional-array key

我的数组看起来像这样:

$items = array();
$items["GB225"] = array (
    "name" => "AAA",
    "img" => "aaa.jpg",
    "includes" => array(
         $things[08] = array (
              "name" => "xxx",
              "text" => "xxxx xx xxxx x x  x xxx x x"
         );
         $things[77] = array (
              "name" => "yyy",
              "text" => "yyyyyy yy yyyyyy y yy yyyyy"
         ) ;
         $things[42] = array (
              "name" => "zzz",
              "text" =>"zz zzzz zzz z z zzz z"
         );
    );
);

我需要得到的是每个第二个数组元素的ID和名称(我需要xxx,ID = 08,yyy,ID = 77,zzz,ID = 42),最好使用PHP。

到目前为止,我最好的猜测是

foreach ($items["includes"] as $thing_id => $thing) { 
     echo $thing["name"];
     echo $thing_id;
}; 

但这只会给我ID“0”,“1”和“2”与“名称”相关联。

我该如何正确地做到这一点?

2 个答案:

答案 0 :(得分:1)

脚本中的$ things变量是什么?此变量似乎未初始化。

您的代码应该是

<?php
$items["GB225"] = array (
    "name" => "AAA",
    "img" => "aaa.jpg",
    "includes" => array(
        8 => array (
              "name" => "xxx",
              "text" => "xxxx xx xxxx x x  x xxx x x"
         ),
         77 => array (
              "name" => "yyy",
              "text" => "yyyyyy yy yyyyyy y yy yyyyy"
         ),
         42 => array (
             "name" => "zzz",
              "text" =>"zz zzzz zzz z z zzz z"
         )
    )
);

foreach ($items['GB225']["includes"] as $thing_id => $thing) { 
    echo $thing["name"];
     echo $thing_id;
}

在这里查看演示https://eval.in/55194

答案 1 :(得分:0)

这就是你的代码的样子:

<?php
$items = array();
$items["GB225"] = array (
    "name" => "AAA",
    "img" => "aaa.jpg",
    "includes" => array(
         8 => array (
              "name" => "xxx",
              "text" => "xxxx xx xxxx x x  x xxx x x"
         ),
         77 => array (
              "name" => "yyy",
              "text" => "yyyyyy yy yyyyyy y yy yyyyy"
         ),
         42 => array (
              "name" => "zzz",
              "text" =>"zz zzzz zzz z z zzz z"
         )
    )
);
echo "<pre>";
print_r($items);

方法1:

foreach ($items as $key => $val) {
  foreach ($val as $key => $anArr) {
    if ($key == "includes")  {
      foreach ($anArr as $key => $val) {
        echo $key . " : " . $anArr[$key]['name'];
      }
    }
  }
}

方法2:

foreach ($items['GB225']["includes"] as $thing_id => $thing) { 
  echo $thing["name"];
  echo $thing_id;
}