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?

Answers


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, a.k.a 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.


Need Your Help

How to determine programmatically whether a particular process is 32-bit or 64-bit

c# process 32bit-64bit

How can my C# application check whether a particular application/process (note: not the current process) is running in 32-bit or 64-bit mode?

Bash: how do I pipe stdout and stderr of one process to two different processes?

bash pipe stdout stderr

I have a process myProcess1 that produces both stdout and stderr outputs. I want to pipe the two output streams into two different downstream processes, myProcess2 and myProcess3, that will massag...