我有一个像
这样的数组$arr[0] = 'summary';
$arr[1]['contact'][] = 'address1';
$arr[1]['contact'][] = 'address2';
$arr[1]['contact'][] = 'country';
$arr[1]['contact'][] = 'city';
$arr[1]['contact'][] = 'pincode';
$arr[1]['contact'][] = 'phone_no';
$arr[2]['work'][] = 'address1';
$arr[2]['work'][] = 'address2';
$arr[2]['work'][] = 'country';
$arr[2]['work'][] = 'city';
$arr[2]['work'][] = 'pincode';
$arr[2]['work'][] = 'phone_no';
使用count($arr)
,它返回3
,但我还需要计算内部数组的值,因此它将返回13
目前为止我试过的是
function getCount($arr,$count = 0) {
foreach ($arr as $value) {
if (is_array($value)) {
echo $count;
getCount($value,$count);
}
$count = $count+1;
}
return $count;
}
echo getCount($arr);
但是它没有像预期的那样工作
您可以使用array_walk_recursive
。这可能有帮助-
$tot = 0;
array_walk_recursive($arr, function($x) use(&$tot) {
$tot++;
});
但是这是一个递归函数,所以你需要小心。
在getCount()
方法中,您没有将数组的计数存储在任何地方。因此,对于每个调用$count
只增加1
。
试试这个
function getCount($arr, $count = 0) {
foreach ($arr as $value) {
if (is_array($value)) {
$count = getCount($value, $count);
} else {
$count = $count + 1;
}
}
return $count;
}
echo getCount($arr);
您在这里所做的是,您没有将值存储在任何变量中,这会使您的代码出现问题,因为您正在以完美的方式
如果你只需要计算前两层,你可以做一个简单的foreach,不需要使用递归函数!:
$count = 0;
foreach( $bigArray as $smallArray ){
if( is_array( $smallArray ) )
$count += count( $smallArray );
else
$count ++;
}
也许我的方法很幼稚,但我只是使用sizeof()
函数。该函数的文档显示,它可以接受第二个参数1
来告诉函数递归地对多维数组进行计数。
所以,要获得'count',你可以简单地写sizeof($arr, 1);
,它应该返回13。
我认识到自己写函数的价值,但是这个内置的PHP方法不是很简洁地解决了问题吗?