简体   繁体   中英

PHP foreach to loop through multi-dimensional array

I have an array in PHP, the var_dump($result) method shows a result like that:

array(6) { [0]=> array(1) { ["Start"]=> string(14) "1/8/2014 10:42" } [1]=> array(1) { ["Driving route"]=> string(14) "1/8/2014 10:59" } [2]=> array(1) { ["Lunch-Rest Break"]=> string(14) "1/8/2014 11:50" } [3]=> array(1) { ["Break"]=> string(14) "1/8/2014 12:03" } [4]=> array(1) { ["Waiting"]=> string(14) "1/8/2014 13:39" } [5]=> array(1) { ["End"]=> string(14) "1/8/2014 14:28" } }

I would like to print each key and its corresponding value so I used a foreach loop to do so but I get the following result :

foreach($result as $activity => $time){
 echo $result[$activity].' / '.$time.'</br>';
}

Array / Array
Array / Array
Array / Array
Array / Array
Array / Array
Array / Array

So how can I do that?

Try in this way. As example of your array I set just two values:

  $arrays = array(
        0=> array("Start"=>'1/8/2014 10:42'),
        1=> array("Lunch-Rest Break"=>'1/8/2014 10:59')

    );
    foreach($arrays as $array){
       foreach ( $array as $key =>$value){
           echo $key .'-'. $value;
       }

    }

You have nested arrays, aka multi-dimensional arrays.

When iterating them, you'll wind up with another array:

foreach($result as $record){
 echo $record[$activity].' / '.$time.'</br>';
}

You can use a recursive function (a function that calls itself) to loop any amount of nested arrays and handle the contents. Here's a sample: Live demo (click).

$myArr = [
  'foo' => 'foo value',
  'bar' => 'bar value',
  'baz' => [
    'nested foo' => 'nested foo value',
    'nested bar' => 'nested bar value'
  ],
  'qux' => 'qux value'
];

function foo($arr) {
  foreach ($arr as $k => $v) {
    if (is_array($v)) {
      foo($v);
    }
    else {
      echo "{$k} = {$v}<br>";       
    }
  }
}

foo($myArr);

You assume an array with key/value pairs, but the array you provide is in fact a normal integer indexed array with as values another array with 1 key/value pair.

You could do this:

foreach ($result as $arr) {
    foreach ($arr as $activity => $time) {
        echo $activity .'/'. $time;
    }
}

The outer loop will run 6 times, the inner loop once per outer loop.

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