0

我拥有的数组如下所示:

$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 和名称(我需要 ID = 08 的 xxx,ID = 77 的 yyy,ID = 42 的 zzz)最好使用 PHP。

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

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

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

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

4

2 回答 2

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

于 2013-10-17T19:27:16.780 回答
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);

方法一:

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

方法二:

foreach ($items['GB225']["includes"] as $thing_id => $thing) { 
  echo $thing["name"];
  echo $thing_id;
}
于 2013-10-17T19:36:15.270 回答