计算php中的子数组

  • 本文关键字:数组 php 计算 php
  • 更新时间 :
  • 英文 :


我有这个输出我想要一个函数来计算所有的孩子谢谢im使用php 7.1版

Array
(
[0] => stdClass Object
(
[slug] => home
[name] => home
[children] => Array
(
[0] => stdClass Object
(
[slug] => contact-us
[name] => Contact Us
[children] => Array
(
[0] => stdClass Object
(
[slug] => new
[name] => new
[children] => Array
(
[0] => stdClass Object
(
[slug] => km
[name] => km
)
)
)
)
)
)
)
)

我想要一个函数来计算所有的孩子谢谢im使用php 7.1版

递归函数每次检测到子函数时都会调用自己来给出答案:

<?php
$data = array (
0 => 
(object) array(
'slug' => 'home',
'name' => 'home',
'children' => 
array (
0 => 
(object) array(
'slug' => 'contact-us',
'name' => 'Contact Us',
'children' => 
array (
0 => 
(object) array(
'slug' => 'new',
'name' => 'new',
'children' => 
array (
0 => 
(object) array(
'slug' => 'km',
'name' => 'km',
),
),
),
),
),
),
),
);
// expects an array as input parameter, per your sample data
function myCount(array $data) {
// static variable keeps its value, similar to a global but not available outside function
static $count = 0;

// this actually counts sibling's children, too.  If you want just the first child, use $data[0]
foreach($data as $d) {
// each array contains an object, so check if the object has the property 'children'
if(property_exists($d,'children')) {

// call the function again to see how many children this child has
myCount($d->children);
$count++; // count here to only count children
}
// counts siblings and children
// $count++;  
}
return $count;
}
print myCount($data);

工作样品http://sandbox.onlinephpfunctions.com/code/b6769a58b617926ba9daaa1399c4fdda56fab225

Php数组计数递归


echo count($array, COUNT_RECURSIVE);

小心你的代码是有stdClass的,你必须转换成数组


$array=json_decode(json_encode($yourdata), true);
echo count($array, COUNT_RECURSIVE);
function count_array($a){
$count = 0;
foreach ($a as $key => $value) {
if(is_array($value)){
$count += count_array($value);
}else if($value instanceof stdClass)
$count += count_array(json_decode(json_encode($value), true));
else{
++$count;
} 
}

return $count;
}

最新更新