类似的问题:多维数组使用PHP查找和更新值

I am at a loss, I have seen similar posts but cannot get my array to have similar structure so that I can implement the solution: I have an array that I create like this:

foreach ($lastsubresult as $lastselect) { array_push($finaldata_array, $subrecord->data ."=>". $lastselect->total );

and when I print this array the output is:

Array ( 
        [0] => aaaaa=>4 
        [1] => aaaaa=>3 
        [2] => aaaaa=>1 
        [3] => tyt=>2 
        [4] => tyt=>3 
      )

I would like to have only single aaaaa's and single tyt's in this array and to have the numbers added and like so:

[0] => aaaaa=>8
[1] => tyt=>5

or even,

[aaaaa] => 8
[tyt] => 5

I have looked at examples like: $merged = array();

foreach ($finaldata_array as $answer) {
    if (isset($merged[$answer['answer']])) {
        $merged[$answer['answer']]['score'] += $answer['score'];
    } else {
        $merged[$answer['answer']] = $answer;
    }
}

var_dump($merged);

but cannot seem to get my array to be similar to the example. The example is exactly what I want to achieve. Could my array_push be wrong.

I will greatly appreciate your help. Thank you very much. Christopher

I can only try to guess what your data is like, but what you're trying to do would be something like this :

foreach($lastsubresult as $lastselect)
{
    $finaldata_array[$subrecord->data] = isset($finaldata_array[$subrecord->data]) ? $finaldata_array[$subrecord->data] + $lastselect->total : $lastselect->total;
}

or, if you don't like / aren't familiar with the ternary operator ? :

foreach($lastsubresult as $lastselect)
{
    if(!isset($finaldata_array[$subrecord->data]))
    {
        $finaldata_array[$subrecord->data] = $lastselect->total;
    }
    else
    {
        $finaldata_array[$subrecord->data] += $lastselect->total;
    }
}