我有一个类似的数组
$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';
Run Code Online (Sandbox Code Playgroud)
使用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);
Run Code Online (Sandbox Code Playgroud)
但它没有按预期工作
你可以用array_walk_recursive它.这可能有所帮助 -
$tot = 0;
array_walk_recursive($arr, function($x) use(&$tot) {
$tot++;
});
Run Code Online (Sandbox Code Playgroud)
但它是一个递归函数,所以你需要小心.
在该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);
Run Code Online (Sandbox Code Playgroud)
您在这里所做的是,您没有将值存储在任何变量中,这会导致您的代码出现问题,因为您处于完美的方式
| 归档时间: |
|
| 查看次数: |
1448 次 |
| 最近记录: |