Is there a way to loop through a multidimensional

2019-01-09 07:30发布

So far, if I have to loop through a multidimensional array, I use a foreach loop for each dimension.

e.g for two dimensions

foreach($array as $key=>$value)
{
    foreach($value as $k2=>$v2)
    {
         echo
    }
}

What do I do when I don't know the depth of the array? ie the depth is variable.

The only thing I can think of is to code a whole stack of loops and to break the loop if the next value is not an array.This seems a little silly.

Is there a better way?

5条回答
萌系小妹纸
2楼-- · 2019-01-09 07:56

Simple function inside array_walk_recursive to show the level of nesting and the keys and values:

array_walk_recursive($array, function($v, $k) {
                                 static $l = 0;
                                 echo "Level " . $l++ . ": $k => $v\n";
                             });

Another one showing use with a reference to get a result:

array_walk_recursive($array, function($v) use(&$result) {
                                 $result[] = $v;
                             });
查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-09 07:59

Based on previous recursion examples, here is a function that keeps an array of the path of keys a value is under, in case you need to know how you got there:

function recurse($a,$keys=array()) 
    {
        if (!is_array($a)) 
            {
                echo implode("-", $keys)." => $a <br>";
                return;
            }
        foreach($a as $k=>$v) 
            {
                $newkeys = array_merge($keys,array($k));
                recurse($v,$newkeys);
            }
    }


recurse($array);
查看更多
可以哭但决不认输i
4楼-- · 2019-01-09 08:05

You can do the below function for loop-through-a-multidimensional-array-without-knowing-its-depth

// recursive function loop through the dimensional array
function loop($array){

    //loop each row of array
    foreach($array as $key => $value)
    {
         //if the value is array, it will do the recursive
         if(is_array($value) ) $array[$key] =  loop($array[$key]);

         if(!is_array($value)) 
         {
            // you can do your algorithm here
            // example: 
             $array[$key] = (string) $value; // cast value to string data type

         }
    }

    return $array;
}

by using above function, it will go through each of the multi dimensional array, below is the sample array you could pass to loop function :

 //array sample to pass to loop() function
 $data = [
  'invoice' => [
      'bill_information' => [
          'price' => 200.00,
          'quantity' => 5
      ],
      'price_per_quantity' => 50.00
  ],
  'user_id' => 20
];

// then you can pass it like this :
$result = loop($data);
var_dump($result);

//it will convert all the value to string for this example purpose
查看更多
唯我独甜
5楼-- · 2019-01-09 08:09

Yes, you can use recursion. Here's an example where you output all the elements in an array:

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

  foreach($a as $v) {
    printAll($v);
  }
}

$array = array('hello',
               array('world',
                     '!',
                     array('whats'),
                     'up'),
               array('?'));
printAll($array);

What you should always remember when doing recursion is that you need a base case where you won't go any deeper.

I like to check for the base case before continuing the function. That's a common idiom, but is not strictly necessary. You can just as well check in the foreach loop if you should output or do a recursive call, but I often find the code to be harder to maintain that way.

The "distance" between your current input and the base case is called a variant and is an integer. The variant should be strictly decreasing in every recursive call. The variant in the previous example is the depth of $a. If you don't think about the variant you risk ending up with infinite recursions and eventually the script will die due to a stack overflow. It's not uncommon to document exactly what the variant is in a comment before recursive functions.

查看更多
再贱就再见
6楼-- · 2019-01-09 08:15

You can use recursion for this problem:

Here is one example

$array = array(1 => array(1 => "a", 2 => array(1 => "b", 2 => "c", 3 => array(1 => "final value"))));

//print_r($array);

printAllValues($array);

function printAllValues($arr) {
    if(!is_array($arr)) {
        echo '<br />' . $arr;
        return;
    }
    foreach($arr as $k => $v) {
        printAllValues($v);
    }
}

It will use recursion to loop through array

It will print like

a
b
c
final value
查看更多
登录 后发表回答