PHP:在foreach循环后无法访问数组元素

时间:2017-04-28 09:20:24

标签: php arrays

我正在打印数组元素

foreach($subcategories as $sucategory){
  print_r($sucategory);
  echo $subcategory[2];
  echo $subcategory[catid];
  echo $subcategory['catid'];
  echo $subcategory["catid"];
  echo $subcategory{"catid"};
  die();
}

上面的代码只打印print_r($subcategory)的值,但它没有回显$ subcategory中catid的值。

Array
(
    [id] => 5
    [name] => 1
    [catid] => 10
    [status] => Y
)

echo $subcategories[0]['catid']; //prints 10 correctly

1 个答案:

答案 0 :(得分:2)

你有错误。你使用$ sucategory和$ subcategory,不同的名字!

复制/粘贴它,它将起作用:

foreach($subcategories as $subcategory){
  print_r($subcategory);
  echo $subcategory["catid"];
  die();
}