1

How do i loop through the following array with a foreach, so it gets printed like this:

Product1 date1 time1
product2 date2 time2
product3 date3 time3
product4 date4 time4

I have been struggling and strugling, i tried double foreaches etc, but somehow i don't get it to work...

Is Anyone able to explain it to me?

Array
(
    [product] => Array
        (
            [0] => product1
            [1] => product2
            [2] => product3
            [3] => product4
        )

    [date] => Array
        (
            [0] => date1
            [1] => date2
            [2] => date3
            [3] => date4
        )

    [time] => Array
        (
            [0] => time1
            [1] => time2
            [2] => time3
            [3] => time4
        )

)
Esocoder
  • 1,032
  • 1
  • 19
  • 40

2 Answers2

3

Something like this should work:

$count = count($data['product']);
for ($i = 0; $i < $count; $i ++) {
    echo $data['product'][$i] . ' ' . $data['date'][$i] . ' ' .$data['time'][$i] . '<br />';
}

To add data-verification/integrity to it (to stop undefined index errors), also check if each index exists in the sub-arrays:

$count = count($data['product']);
for ($i = 0; $i < $count; $i++) {
    $date = isset($data['date'][$i]) ? ' ' . $data['date'][$i] : '';
    $time = isset($data['time '][$i]) ? ' ' . $data['time '][$i] : '';
    echo $data['product'][$i] . $date . $time . '<br />';
}
newfurniturey
  • 37,556
  • 9
  • 94
  • 102
  • With the updated answer and corrected array access after your first update, ok +1. – Robert Aug 17 '12 at 18:47
  • Thanx man! Exactly what i was looking for. I couldn't understand how to do it with just a for(), but now i do! – Esocoder Aug 17 '12 at 19:13
3

simple

<?php
    foreach($array['product'] as $num => $prod){
        echo $prod." ".$array['date'][$num]." ".$array['time'][$num];
    }
?>
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107