获取PHP或JS中的json密钥和对象的总数

时间:2015-10-17 11:53:22

标签: 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 = curl_exec($ch);
curl_close($ch);
$data = json_decode($data, true);
echo count($data['planes']);

Json Structure Image

2 个答案:

答案 0 :(得分:3)

在Javascript中,计算对象的键:

Object.keys(myObj).length

或者,在PHP中,将其转换为数组并计算它:

$json = json_decode($myStr);
count($json);

您可以使用数字索引和$json访问count()数组的成员,或者再次解码它们等等:

echo count($json[2])

true传递给json_decode()以创建关联数组(您必须使用字符串键访问,而不是数字索引)。

答案 1 :(得分:0)

使用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 ;
}