Javascript 获取PHP或JS中json键和对象的总数
我有一个Json,它的结构如下:(附图) 我希望总密钥为0,1,11 我有一段代码,它给了我输出“3”,但我想要这3个对象中的全部对象:Javascript 获取PHP或JS中json键和对象的总数,javascript,php,json,Javascript,Php,Json,我有一个Json,它的结构如下:(附图) 我希望总密钥为0,1,11 我有一段代码,它给了我输出“3”,但我想要这3个对象中的全部对象: $url = '//json url'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $data
$url = '//json url';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
$data = json_decode($data, true);
echo count($data['planes']);
在Javascript中,计算对象的键:
Object.keys(myObj).length
或者,在PHP中,将其转换为数组并计数:
$json = json_decode($myStr);
count($json);
您可以使用数字索引和count()
对$json
数组的成员进行访问,或者再次对其进行解码,等等:
echo count($json[2])
将true
传递到json\u decode()
以创建关联数组(必须使用字符串键而不是数字索引来访问该数组)。使用Object.keys()方法。它返回对象中所有键的数组,然后使用length方法获得数组长度
比如说
var x = {
0: {
x: 1,
y: 1
},
1: {
x: 1,
y: 1
},
1: {
x: 1,
y: 1
},
}
var total = 0;
for( var obj in x ) {
total += Object.keys(x[obj]).length ;
}
在PHP7.2+中,需要在json_decode
的第二个参数中传递true
,才能返回数组。count()
函数将针对不可计数类型发出E_警告,new stdclass
不实现可计数接口。()