dongqian8265 2016-03-31 02:25
浏览 29
已采纳

多维数组的递归计数元素

I try to make recursive function to count elements on array "levels". But can't do that for two hours already. Check example array:

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

The resulting array that count elements on different levels will be:

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

I made function for count total array elements, but no idea how to count each "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条回答 默认 最新

  • douji4223 2016-03-31 09:57
    关注

    Another solution using 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条)

报告相同问题?