Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Hello 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 please?

share|improve this question

4 Answers 4

up vote 4 down vote accepted

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;
       }

    }
share|improve this answer
1  
This is better than mine because I assumed he knew what the keys were. This will work when the keys are unknown –  helion3 Feb 1 at 22:26

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>';
}
share|improve this answer
    
This is wired using your code I get " / " –  OussamaLord Feb 1 at 22:25

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);
share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.