Reputation: 1095
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?
Upvotes: 0
Views: 267
Reputation: 2149
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.
Upvotes: 0
Reputation: 43745
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);
Upvotes: 0
Reputation: 5260
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;
}
}
Upvotes: 4
Reputation: 37361
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>';
}
Upvotes: 0