多维数组的递归计数元素

时间:2016-03-31 02:25:33

标签: php arrays multidimensional-array count

我尝试使用递归函数来计算数组“级别”上的元素。但已经两个小时都做不到了。检查示例数组:

Array ( 
    [0] => Array ( 
        [0] => Array ( 
            [0] => Array ( ) 
            [1] => Array ( ) 
        ) 
        [1] => Array ( ) 
    ) 
    [1] => Array ( 
        [0] => Array (
            [0] => Array (
                [0] => Array ( )
                [1] => Array ( )
            )
        )
    ) 
)

计算不同级别元素的结果数组将为:

Array ([0] => 2, [1] => 3, [2] => 3, [3] => 2)

我为count total array元素创建了函数,但不知道如何计算每个“level”

function countTotalArr($arr, $lvl) {
    if ($lvl != 0) $cnt = 1; 
    else $cnt = 0; // don't count zero level 

    for ($i = 0; $i < count($arr); $i++)
        $cnt += countArr($arr[$i], $lvl + 1);

    return $cnt;
}

$total = countTotalArr($referralsCount, 0);

2 个答案:

答案 0 :(得分:2)

使用while的另一种解决方案:

// $array is your array at the beginning of iteration

$depthMap = [];
$currentDepth = 0;
while(true) {
    $depthMap[$currentDepth] = count($array);

    $carry = [];
    foreach($array as $item) {
        if(is_array($item)) {
            $carry = array_merge($carry, $item);
        }
    }

    if(count($carry) < 1) {
        break;
    }

    $array = $carry;
    $currentDepth++;
}

答案 1 :(得分:1)

试试这段代码:

<?php

$array = Array ( 
    0 => Array ( 
        0 => Array ( 
            0 => Array ( ) ,
            1 => Array ( ) ,
        ) ,
        1 => Array ( ) ,
    ) ,
    1 => Array ( 
        0 => Array (
            0 => Array (
                0 => Array ( ),
                1 => Array ( ),
            ),
        ),
    ) ,
);

function countTotalArr($arr, $lvl) 
{
    $result = array();
    $countOnLevel = count($arr);

    $result[$lvl] = $countOnLevel;

    $tempArray = array();
    foreach($arr as $index => $singleArray)
    {
        foreach($singleArray as $singleSubArray)
        if(is_array($singleSubArray))
            $tempArray[] = $singleSubArray;
    }

    if(!empty($tempArray))
    {
        $levelTemp = $lvl + 1;
        $result = array_merge($result, countTotalArr($tempArray, $levelTemp));
    }

    return $result;
}

$total = countTotalArr($array, 0);

echo '<pre>';
print_r($total);

print_r($total)的结果是:

Array
(
    [0] => 2
    [1] => 3
    [2] => 3
    [3] => 2
)
相关问题