所以我一直试图计算这个对象阵列多年,似乎没有什么对我有用......
stdClass Object
(
[type] => champion
[version] => 5.24.2
[data] => stdClass Object
(
[Thresh] => stdClass Object
(
[id] => 412
[key] => Thresh
[name] => Thresh
[title] => the Chain Warden
[info] => stdClass Object
(
[attack] => 5
[defense] => 6
[magic] => 6
[difficulty] => 7
)
)
[Aatrox] => stdClass Object
(
[id] => 266
[key] => Aatrox
[name] => Aatrox
[title] => the Darkin Blade
[info] => stdClass Object
(
[attack] => 8
[defense] => 4
[magic] => 3
[difficulty] => 4
)
)
[Tryndamere] => stdClass Object
(
[id] => 23
[key] => Tryndamere
[name] => Tryndamere
[title] => the Barbarian King
[info] => stdClass Object
(
[attack] => 10
[defense] => 5
[magic] => 2
[difficulty] => 5
)
)
[Ezreal] => stdClass Object
(
[id] => 81
[key] => Ezreal
[name] => Ezreal
[title] => the Prodigal Explorer
[info] => stdClass Object
(
[attack] => 7
[defense] => 2
[magic] => 6
[difficulty] => 7
)
)
)
)
我想要计算的是data
的长度。
Plot Twist: count($array->data)
无法正常工作。
如果它是正确的,它应该返回3.提前谢谢!
答案 0 :(得分:2)
在您的情况下,data
是一个对象。把它投射到数组:
$count = count((array) $array->data);
另一种方法是使用get_object_vars
$count = count(get_object_vars($array->data));
答案 1 :(得分:1)
不是那么难,你可以这样做:
$object = [ .... ]; // The object you show above.
function countElements($object) {
return count(get_object_vars($object));
}
$count = countElements($object);
那应该能得到答案。
答案 2 :(得分:1)
在代码下方使用:
count((array)$array->data);
而不是:
count($array->data);
答案 3 :(得分:1)
只需使用count((array) $array->data);