【发布时间】:2015-08-17 11:41:45
【问题描述】:
我有一个类似 as 的数组
$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);
但它没有按预期工作
【问题讨论】:
-
如果您也想计算内部数组中的值(深度无关紧要),您可以将第二个参数作为
count($your_array, COUNT_RECURSIVE)传递给count。如果您只想计算数组的内部值,您可以从递归计数中减去正常计数。 -
@Andrew 这将返回
17 -
检查这个[多维数组计数][1][1]:stackoverflow.com/questions/9062770/…