I'm stuck with sorting my array to taking out unique values and process the associated value to an accumulative value.
Source code :
while($row1 = mysql_fetch_array($result1))
{
$row1[8] = $row1[8] / 60;
echo "<tr>".
"<td>".$row1[0] . "</td>".
"<td>".$row1[1] . "</td>".
"<td>".$row1[2] . "</td>".
"<td>".$row1[3] . "</td>".
"<td>".$row1[4] . "</td>".
"<td>".$row1[5] . "</td>".
"<td>".$row1[6] . "</td>".
"<td>".$row1[7] . "</td>".
"<td>".$row1[8] . "</td>".
"<td>".$row1[9] . "</td>";
$counters = array();
$counters[$row1[9]] += $row1[8];
arsort($counters);
var_dump($counters);
The var dump is as such :
array(1) { ["derek"]=> int(2) }
array(1) { ["garyhui"]=> float(0.5) }
array(1) { ["nikole"]=> int(1) }
array(1) { ["tony"]=> int(4) }
array(1) { ["tony"]=> int(2) }
array(1) { ["tony"]=> float(3.5) }
array(1) { ["tony"]=> float(2.5) }
I need the end result to be smth similar like
Derek : 2
Garyhui : 0.5
Nikole : 1
Tony : 12 <-- note this number was able to accumulate on its own based on the previous array indexs association. Appreciate any help given !
You keep redefining $counters to empty array, because you keep doing $counters = array()
inside the loop. That's why they don't add up. You have to remove that single line of code and move it to somewhere above the loop. Exactly like this:
$counters = array();
while($row1 = mysql_fetch_array($result1))
{
$row1[8] = $row1[8] / 60;
echo "<tr>".
"<td>".$row1[0] . "</td>".
"<td>".$row1[1] . "</td>".
"<td>".$row1[2] . "</td>".
"<td>".$row1[3] . "</td>".
"<td>".$row1[4] . "</td>".
"<td>".$row1[5] . "</td>".
"<td>".$row1[6] . "</td>".
"<td>".$row1[7] . "</td>".
"<td>".$row1[8] . "</td>".
"<td>".$row1[9] . "</td>";
$counters[$row1[9]] += $row1[8];
arsort($counters);
var_dump($counters);
Use array_key_exists() to check for existing key value:
#like @Erik said, place this out of while loop,
#keeping it inside while makes it empty in every loop
$counters = array();
while($row1 = mysql_fetch_array($result1))
{
/*
Your echo code here
*/
if(array_key_exists($row1[9],$counters)){
#if exists, accumulate value of current key
$counters[$row1[9]] += $row1[8];
}
else
{
#if does not exist, create new key
$counters[$row1[9]] = $row1[8];
}
}