Jump to content

Foreach And For


chasethemetal

Recommended Posts

Hey all! So I have this old solution someone helped me with a while back. Here is the working solution... $results = mysql_query($data) or die(mysql_error()); $records = array(); while($info = mysql_fetch_array($results)) { if (!isset($records[$info['date']])) $records[$info['date']] = array(); $records[$info['date']][] = $info['SUM(count)']; } foreach ($records as $date => $count) { echo "['" . $date . "', "; for ($a = 0; $a < count($count); $a++) echo "$count[$a], "; echo "],"; } } This successfully spits the info I need out in this format ['2011-11-28', 2, 5, ], ['2011-11-27', 4, 2, ], and so on. My new question is I would like to have this all assigned to one variable so I can call it out of the loops. I would like it to work like this... echo $countData; and it would have all of that combined inside that. I've tried so many combinations to attempt to get it to work outside of the loop but I can't figure it out. I know this doesn't work but this is my thoughts. foreach ($records as $date => $count) { $part1 = "['" . $date . "', "; for ($a = 0; $a < count($count); $a++) $part2 = "$count[$a], "; $part3 = "],"; $countData .= $part1.$part2.$part3; } I've tried all sorts of combination methods. And I can't seem to get it right. Any help again is always appreciated!

Link to comment
Share on other sites

everytime loop iterate $countData looses its previous value.you can store it as array something like..$countData[]=$p1.$p2.$p3; to use later.

Link to comment
Share on other sites

This works. But it is not dynamic. foreach ($records as $date => $count) { $part1 = "['" . $date . "', "; $part2 = "$count[0], $count[1], "; $part3 = "],"; $countData .= $part1.$part2.$part3; } echo $countData; The problem here is $count[] needs to dynamically increase based on the data. This is why we put... for ($a = 0; $a < count($count); $a++) {echo "$count[$a], "; //this is $part2} But I can't seem to combine all of these elements into one variable $countData to be called outside the loops...

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...