2

如何使用数组索引访问数组元素值?

<?
$json = '{
    "dynamic":{
       "pageCount":"12",
       "tableCount":"1"
    }
}';

$arr = json_decode($json, true);

echo $arr['dynamic']['pageCount']; // working
echo $arr[0]['pageCount']; // not working
?>

我不知道“动态”中有什么,所以我想动态访问 pageCount 值?

4

2 回答 2

13

array_values是您正在寻找的功能

例子:

<?php
$json = '{
    "dynamic":{
       "pageCount":"12",
       "tableCount":"1"
    }
}';

$arr = json_decode($json, true);
echo $arr['dynamic']['pageCount']; // working

$arr = array_values($arr);
echo $arr[0]['pageCount']; // NOW working

?>
于 2012-09-05T08:31:38.950 回答
1
$arr = json_decode($json, true);
foreach ($arr as $key => $value) {
    if (isset($value['pageCount'])) {
        //do something with the page count
    }
}

如果结构始终是单个嵌套的 JS 对象:

$obj = current($arr);
echo $obj['pageCount'];
于 2012-09-05T08:29:52.417 回答