Current Array Output:
[0] => Array
(
[id] => 165 <-- first occurrence
[score] => 3.813 <-- first value
)
[1] => Array
(
[id] => 167
[score] => 3.772
)
[2] => Array
(
[id] => 165 <-- second
[score] => 4.421 <-- second value
)
Desired Updated Array's Output after some php function:
[0] => Array
(
[id] => 165 <-- update this key
[score] => 8.234 <-- with $ary[0][score] + $ary[2][score]
)
[1] => Array
(
[id] => 167
[score] => 3.772
)
Since the id key was updated we don't need the $ary[2][id]
and $ary[2][score]
, so remove it.
Is there a magical function? or Should we write a special function to make this happen? Thanks!
For a general purpose function which tots up all of the records that share the same id
value:
(NB: probably not idiomatic PHP, but it does work)
function totup($a) {
// create temporary array keyed on ID, containining sum of scores
$tmp = array();
foreach ($a as $row) {
$id = $row['id'];
$score = $row['score'];
$tmp[$id] += $score;
}
// then convert that array back to (id, score) tuples
$res = array();
foreach ($tmp as $id => $score) {
$res[] = array(id => $id, score => $score);
}
return $res;
}
Test run:
$tmp = array(
array(id => 165, score => 3.813),
array(id => 167, score => 3.772),
array(id => 165, score => 4.421));
$foo = totup($tmp);
print_r($foo);
Array
(
[0] => Array
(
[id] => 165
[score] => 8.234
)
[1] => Array
(
[id] => 167
[score] => 3.772
)
)
$ary[0][score] += $ary[2][score];
unset(yourArray[2]);