Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP recursion print all elements of a multidimensional array with keys

I found the following code, which prints all the elements of an array fine. How can I modify it to print a key one time and then all the values corresponding to the key, then another key, then all values corresponding to key? I also would like to modify it so it only prints the first 9 values (no more than this) for each key.

 function printAll($a) {
  if (!is_array($a)) {
    echo $a, ' ';
     return;
   }

   foreach($a as $v) {
   printAll($v);
  }
 }
like image 905
user1605871 Avatar asked Dec 01 '22 20:12

user1605871


2 Answers

I am assuming you want something non-programming humans can make some sort of sense out of.

function pretty_dump($arr, $d=1){
    if ($d==1) echo "<pre>";    // HTML Only
    if (is_array($arr)){
        foreach($arr as $k=>$v){
            for ($i=0;$i<$d;$i++){
                echo "\t";
            }
            if (is_array($v)){
                echo $k.PHP_EOL;
                Pretty_Dump($v, $d+1);
            } else {
                echo $k."\t".$v.PHP_EOL;
            }
        }
    }
    if ($d==1) echo "</pre>";   // HTML Only
}

Usage:

$myarray=array(
    'mammals'=>array(
        'cats'=>array(
            'cheetah',
            'lion',
            'cougar'
        ),
        'dogs'=>array(
            'big'=>'Scooby',
            'small'=>'chihuahua',
            'medium'=>array(
                'pumi',
                'bulldog',
                'boxer'
            )
        ),
    ),
    'fish'=>'fish',
    'birds'=>array(
        'flying'=>array(
            'mallard',
            'condor',
            'gull'
        ),
        'nonflying'=>'emu'
    )
);

pretty_dump($myarray);

Output:

    mammals
        cats
            0   cheetah
            1   lion
            2   cougar
        dogs
            big Scooby
            small   chihuahua
            medium
                0   pumi
                1   bulldog
                2   boxer
    fish    fish
    birds
        flying
            0   mallard
            1   condor
            2   gull
        nonflying   emu
like image 198
ABraut Avatar answered May 24 '23 04:05

ABraut


function printAll($a) {
    if (!is_array($a)) {
        echo $a, ' ';
        return;
    }

    foreach($a as $k => $value) {
         if($k<10){
             printAll($k);
             printAll($value);
        }
    }
}
like image 36
v0d1ch Avatar answered May 24 '23 04:05

v0d1ch