Jump to content

Logic error


182x

Recommended Posts

Hey guys, I was trying to get the code below to count the  number of times a year occurs in each query and then store the total amount along with the year. So if table 1 had 2007 appear 3 times and table2 had 2007 appear 3 times the final out put should be in that $amountAll[] = 6 and $amountYear = 2007.

 

I was just wondering where i went wrong?

 

	$getAll = "SELECT year, count(*) FROM table1 GROUP BY year";
	$queryAll = mysql_query($getAll, $link_id) or die(mysql_error());

	$getAll2 = "SELECT year, count(*) FROM table2 GROUP BY year";
	$queryAll2 = mysql_query($getAll2, $link_id) or die(mysql_error());
	$rowAll3[400];

$years = array();
while($rowAll = mysql_fetch_array($queryAll))
{
   $years[$rowAll['year']] = $rowAll['count(*)'];
}
while($rowAll = mysql_fetch_array($queryAll))
{
   if(isset($years[$rowAll2['year']]))
   {
      $years[$rowAll2['year']] += $rowAll2['count(*)'];
   }
   else
   {
      $years[$rowAll2['year']] = $rowAll2['count(*)'];
   }
}
ksort($years);  // sort array by keys (years) 


   foreach($years as $year => $count)
{
   $amountAll[] = $count;
$yearAll[] = $year;
}

Link to comment
https://forums.phpfreaks.com/topic/62216-logic-error/
Share on other sites

first i think that you should put both result sets into a single array. use array merge

 

simple way to create an array of your results:

 

$arr1 = array();
$count = mysql_num_rows($queryAll);
for($i =0; $i < $count; $i++){
$arr1[] = $row = mysql_fetch_assoc($queryAll);
}

 

do that for both, then loop through that array and when you find your year, increment the counter. (if youre going to loop through it more than once, you could remove that index once it is found so that your next loop is smaller - not important, just a thought)

 

 

Link to comment
https://forums.phpfreaks.com/topic/62216-logic-error/#findComment-309690
Share on other sites

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.