Page 1 of 1

Loop through array vertically

Posted: Thu Oct 11, 2012 5:20 am
by yii_king
I have an array which contains data retrieved from a database table.

I know that I can retrieve the values by a normal foreach loop like this which is then going through the array row by row.

Code: Select all

foreach ($arr as $val) {
echo $val->date.<br/>;
echo $val->hour1.<br/>;
echo $val->hour2.<br/>;
}
However, I am using a jquery plugin which requires me to print out the values vertically instead. I'm trying this:

Code: Select all

// Columns are 2012-10-11 and 2012-10-12 and the data below goes straight under each column
foreach ($arr as $val) {
$date = $val->date;
foreach ($date as $v) {
echo '['.$v->hour1.', '.$v->hour1.'],'; // Each day shows hour 1
echo '['.$v->hour2.', '.$v->hour2.'],'; // Each day shows hour 2
}
}
However, this is not working. Any ideas?

Re: Loop through array vertically

Posted: Thu Oct 11, 2012 8:00 pm
by requinix
So you want to turn

Code: Select all

      date | hour1 |    hour2
-----------+-------+---------
2012-10-11 |   foo |      bar
2012-10-12 |   baz | whatever

Code: Select all

[{"date":"2012-10-11","hour1":"foo","hour2":"bar"},{"date":"2012-10-12","hour1":"baz","hour2":"whatever"}]
into

Code: Select all

   2012-10-11 |       2012-10-12
--------------+-----------------
hour1 | hour2 | hour1 |    hour2
------+-------+-------+---------
  foo |   bar |   baz | whatever

Code: Select all

{"2012-10-11":[{"hour1":"foo","hour2":"bar"}],"2012-10-12":[{"hour1":"baz","hour2":"whatever"}]}