I use an array to hold two values from a database search: key = percentage, and value = username. I want to sum all of the percentage (key) values, and it has been suggested that the best way to do this is using the foreach loop. Unfortunately, I really have a hard time wrapping my head around its use.

Can anyone suggest how I can iterate through a foreach loop and sum up all of the percentages based on a matching username value.

Thanks in advance for any help.
Revez

    foreach($array  as $percentage => $username){
    $total[] = $percentage;
    }
    
    $total = array_sum($total); 
    
    echo $total;
    

      Assuming I understand the question correctly:

      $sum = 0;
      foreach($array as $key => $value)
      {
         $sum += $key;
      }
      echo $sum;
      

        Thanks to all for the suggestions.

        However, using the code posted, I get a sum of all of the values in the array.

        Sorry if my original posting wasn't clear.

        I have an array named rank that I use to gold the values of two variables: percentage and username. Percentage is the key and usename is the value. This array has more than one element with matching values (i.e. usernames). I want to sum up only the percentages in the array that have a matching value (username).

        Thanks again for the help, and I hope that my question makes more sense this time around.

        revez

          could you post your code so far...

            Hello,

            I create an array named rank:

            $rank = array();
            

            I then take two values from various database searches, and populate the rank array as follows:

            $rank[$percentage] = $username;
            

            revez

            Best a I can figure, the code I need to use should look something like this:

              foreach ($rank as $percentage => $username) {]
                if($???????? == $username) {
                  $sum += $percentage;
                }
              }
            
            

            Its filling in the $???????? part that I can't figure out.

            revez

              $result = array();
              
              foreach($rank as $percent => $username)
              {
                  if(!isset($result[$username]))
                      $result[$username] = $percent;
                  else
                      $result[$username] += $percent;
              }
              
              print_r($result);

              Not guaranteed to work, but should push you the right way.

                OK, it looks like we're making some progress! The output seems to be accurate, but there appears to be one small problem - it looks like username is now the key, and I want to sort my results by percentage (highest to lowest).

                None of the functions that I have tried (ksort, natsort, asort, etc.) will work.

                revez

                  natsort($result) should sort the $result array by percentages.... have you done:

                  print_r($result);
                  natsort($result);
                  print_r($result);

                    Yes, I have used the natsort($result), and it does appear to list the results in percentage order, but from lowest down to highest. I need the list to display from highest to lowest, and none of the sorting functions (or combinations of them) will display highest to lowest.

                    revez

                      Oh, well that's not "a problem", that's just a case of "it's not what I want exactly".

                      Just reverse the array ๐Ÿ˜‰

                      natsort($result);
                      $result = array_reverse($result, true);

                      EDIT: Note that the second parameter of "true" in the array_reverse function is required to keep the array keys.

                        Here is the code that I am using. It is doing most of what it should except for the sorting issue. Also, when I call print ($rows[key]);, I get the username instead of the percentages.

                        <?php
                        $result = array();							ยจ
                        
                        foreach($rank as $percentage => $username) {
                        
                        if(!isset($result[$username])) {
                        $result[$username] = $percentage;
                        
                        } else {
                        $result[$username] += $percentage;
                        }										
                        }								
                        
                        krsort($result);													
                        for ($m=1; $m <= count($result); $m++) {
                        
                        $rows = each($result);						
                        
                        if(!empty($rows[key])) {
                        
                        echo '<tr>';
                        echo '<td height="22" width="5"></td>';
                        echo "<td class=\"mid_blue_02\" width=\"50\" align=\"left\" valign=\"middle\" bgcolor=\"#EBEBEB\">&nbsp;$m</td>";
                        echo "<td class=\"mid_blue_02\" width=\"".(($cell_001 - 80) * 0.50)."\" align=\"left\" valign=\"middle\" bgcolor=\"#EBEBEB\">";
                        print ($rows[key]);
                        echo "</td>";
                        echo "<td class=\"mid_blue_02\" width=\"".(($cell_001 - 80) * 0.50)."\" align=\"left\" valign=\"middle\" bgcolor=\"#EBEBEB\">";
                        print ($rows[value]);
                        echo "%</td>";
                        echo '<td width="15" bgcolor="#EBEBEB"></td>';				
                        echo '</tr>';
                        echo '<tr>';
                        echo '<td colspan="4" height="1" width="'.$cell_001.'" bgcolor="#CCCCCC"></td>';
                        echo '<td width="15" bgcolor="#EBEBEB"></td>';
                        echo '</tr>';							
                        }								
                        }
                        ?>
                        

                          Hey there bpat1434,

                          We must have been posting at the same time, and I didn`t see your last message. I implemented the fix that you suggested (using array_reverse), and everything is working exactly as required.

                          I must have spent over 6 hours trying to figure this out on my own, but at least it is now working. Thanks so much for your help in resolving this!!!

                          Cheers!
                          revez ๐Ÿ™‚

                            Write a Reply...