PHP:如何使用数组索引访问数组元素值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12277268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:12:23 来源:igfitidea点击:
PHP: How to access array element values using array-index
提问by Shiv
How to access array element values using array-index?
如何使用数组索引访问数组元素值?
<?
$json = '{
"dynamic":{
"pageCount":"12",
"tableCount":"1"
}
}';
$arr = json_decode($json, true);
echo $arr['dynamic']['pageCount']; // working
echo $arr[0]['pageCount']; // not working
?>
I will not know what is there in 'dynamic', so i want to access pageCount values dynamically?
我不知道“动态”中有什么,所以我想动态访问 pageCount 值?
回答by Tufan Bar?? Y?ld?r?m
array_valuesis function you are looking for
array_values是您正在寻找的函数
Examples:
例子:
<?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
?>
回答by Dan Grossman
$arr = json_decode($json, true);
foreach ($arr as $key => $value) {
if (isset($value['pageCount'])) {
//do something with the page count
}
}
If the structure is always a single nested JS object:
如果结构始终是单个嵌套的 JS 对象:
$obj = current($arr);
echo $obj['pageCount'];

