Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/236.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取PHP或JS中json键和对象的总数_Javascript_Php_Json - Fatal编程技术网

Javascript 获取PHP或JS中json键和对象的总数

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

我有一个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 = 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
不实现可计数接口。()