php - Group and sum duplicate elements in a for loop -


i have loop so:

for((int) $i = 0; $i < $number_of_updates; $i++)  {          //query here         $result = mysql_query($query);         list($name) = mysql_fetch_row($result);         $points = 1;          //some functions execute here... ,          //store results in session show on other page         $output = $points.' times '.$name;         $_session['item'][] = $output;  } 

and show results on view page so:

foreach (array_unique($_session['item']) $output)  {     echo ('<p>'.$output.'</p>');  } 

it echoes results out of loop so:

1 times foo

1 times foo

1 times bar

1 times foo

etc...

now question. how sum results don't duplicate? instead shown so:

3 times foo

1 times bar

user array_count_values

for(/*(int) <- not neccessary (c++ background?) */ $i = 0; $i < $number_of_updates; $i++)  {     // code     $_session['item'][] = $name;  }  foreach(array_count_values($_session['item']) $name => $times)     echo ('<p>'.$times.' times '.$name.'</p>'); 

of course counting values directly more memory , time efficient. version neccessary if somehow need preserve order of elements.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

mysql - Pass value between different pages (form) with PHP -