Jump to content

looping through one-dimensional array


stevieontario

Recommended Posts

hello freaks,

 

I have a four-element array, which is the result of a mysql query. The array is like below. (This is of course just a snippet to show the structure; the hours of course go up to 24, then repeat; there are about ten days' worth of data.)

 

 

 

Array
(
[dayname] => day1
[hour] => 1
[widtype] => type1
[Output] => 20
)
Array
(
[dayname] => day1
[hour] => 2
[widtype] => type1
[Output] => 9
)
Array
(
[dayname] => day1
[hour] => 1
[widtype] => type2
[Output] => 450
)
Array
(
[dayname] => day1
[hour] => 2
[widtype] => type2
[Output] => 650
)

 I want to loop through this data and output each hour's data in a separate line, like below (I included the headings just for clarity):

 

 

Day Hour Type1_total Type2_total day1 1 20 450 day1 2 9 650

 

 

... and can't seem to make this happen. Here's the code I've written:

		$prevday = '';
		while ( $row = mysql_fetch_assoc($result))
	{	
		extract($row);
		$currentday = $row['dayname'];
		$currenthour = $row['hour'];
		$currentwid = $row['widtype'];
		while($currentday !== $prevday){
		 for($currenthour = 1; $currenthour <=24; $currenthour++){
					
		if($row['widtype'] == 'type1'){	$type1_total = $row['Output'];}
		if($row['fuel'] == 'type2'){$type2_total = $row['Output'];}
			print "<pre>";
			echo "$currentday, $currenthour, $type1_total, $type2_total";
			print "</pre>";
					}
		$prevday = $currentday;
			}
			}

... and here's what it outputs:

 

day1, 1, 20, ,
day1, 2, 20, ,

 

Clearly I have written this loop wrong but have banged my head against it for a while and wonder if it's just not possible to do what I want.

 

Any suggestions would be hugely appreciated!

Link to comment
https://forums.phpfreaks.com/topic/288565-looping-through-one-dimensional-array/
Share on other sites

 

I want to loop through this data and output each hour's data in a separate line, like below (I included the headings just for clarity): 

 

 

Day Hour Type1_total Type2_total day1 1 20 450 day1 2 9 650

Not very clear from where I'm sitting. Can you post a better example

You didn't show the query you used so this may not work out-of-the-box. But, you should be able to change your query to do the calculations for you. Give this a try

 

 

SELECT dayname, hour,
       SUM(IF(widtype='type1', Output, 0)) AS type1_total,
       SUM(IF(widtype='type2', Output, 0)) AS type2_total
FROM table
GROUP BY dayname, hour

Archived

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

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.