简体   繁体   中英

Traverse multi dimensional array recursively without using foreach

I have an array like this and the code using foreach loop.

$arr = array( array ( array( 'CAR_TIR', 'Tires', 100 ),
           array( 'CAR_OIL', 'Oil', 10 ),
           array( 'CAR_SPK', 'Spark Plugs', 4 )
          ),
       array ( array( 'VAN_TIR', 'Tires', 120 ),
           array( 'VAN_OIL', 'Oil', 12 ),
           array( 'VAN_SPK', 'Spark Plugs', 5 )
          ),
       array ( array( 'TRK_TIR', 'Tires', 150 ),
           array( 'TRK_OIL', 'Oil', 15 ),
           array( 'TRK_SPK', 'Spark Plugs', 6 )
          )
      );


function recarray($array)
{
    foreach($array as $key=>$value)
    {
        if(is_array($value))
        {
            RecArray($value);
        }
        else
        {
            echo "key = $key value = $value";
       }
    }
}
recarray($arr);

I have to traverse the array using recursion and without using foreach.

Simple depth first search:

function DFS($array) {      
    for ($i = 0; $i < count($array); $i ++) {
        if (is_array($array[$i])) {
            DFS($array[$i]);
        }
        else {
            echo "key: ".$i.", value: ".$array[$i]."<br />";
        }
    }
}

What about array_walk_recursive() ? it can apply function to each element of the array:

function test_print($value, $key)
{
    echo "key = $key value = $value";
}

array_walk_recursive($arr, 'test_print');

not tested

我会使用while循环 - 就像

while($i < count($array)) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM