2016-03-31 11 views
0

Ich versuche, rekursive Funktion zum Zählen von Elementen auf Array "Ebenen" zu machen. Aber das kann man schon seit zwei Stunden nicht mehr machen. Überprüfen Beispiel Array:Rekursive Zählelemente des mehrdimensionalen Arrays

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

Das resultierende Array, das Elemente auf verschiedenen Ebenen zählen wird:

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

Ich habe Funktion für Zählung Gesamt Array-Elemente, aber keine Ahnung, wie jede „Ebene“ zählen

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); 

Antwort

2

Eine andere Lösung mit 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

Versuchen Sie diesen Code:

<?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); 

Ergebnis print_r($total) ist:

Array 
(
    [0] => 2 
    [1] => 3 
    [2] => 3 
    [3] => 2 
) 
Verwandte Themen