我正在尝试计算多维数组中的嵌套元素。起初我以为我可以使用COUNT_RECURSIVE,但这算作一切。所以我尝试了两种不同的方法,它们都没有吸引我。有没有更好的方法呢?
$count = 0;
foreach ($topics as $t) {
foreach ($t as $c) {
$count++;
}
}
echo $count;
// or
echo (count($topics, COUNT_RECURSIVE)-count($topics));
答案 0 :(得分:2)
function countNested($arr) {
return (count($arr, COUNT_RECURSIVE) - count($arr));
}
答案 1 :(得分:0)
我会写这段代码:
$count = 0;
foreach ($topics as $t) {
$count+= count($t);
}
echo $count;
答案 2 :(得分:0)
//以下示例将计算一维或二维数组
$values_count = (count($values, COUNT_RECURSIVE) - count($values)?:count($values));