2

我无法为该线程获得合适的标题(帮助我)。我无法描述这个问题,所以这里是我的问题的例子。

我的数组:

Array ( [0] => Array ( [answer] => a [score] => 3 )
[1] => Array ([answer] => b [score] => 4 ) 
[2] => Array ( [answer] => h [score] => 3) 
[3] => Array ( [answer] => a [score] => 4 ))
...

我想得到这样的输出:

Array ( [0] => Array ( [answer] => a [score] => 7 )
[1] => Array ([answer] => b [score] => 4 ) 
[2] => Array ( [answer] => h [score] => 3))
...

您可以在索引键 0 中看到 score 子键的变化。这是因为索引键 0 和 3 的答案子键中有两个值“a”。由于两者的总和 (3+4),分数变为 7 . 真的我对此一无所知,对不起我的英语并感谢您的帮助。随意发表评论。:)

4

3 回答 3

3
$merged = array();

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

var_dump($merged);
于 2013-03-26T07:57:11.057 回答
1

检查这个答案,不使用循环:

$arr  = array ( array ( 'answer' => 'a', 'score' => 3 ),
                array ( 'answer' => 'b', 'score' => 4 ), 
                array ( 'answer' => 'h', 'score' => 3), 
                array ( 'answer' => 'a', 'score' => 4 ));

$t = array_reduce($arr, function($result, $item) {
        if(array_key_exists($item['answer'],$result)){
           $result[$item['answer']]    = array('answer' => $item['answer'], 'score' => $item['score']+$result[$item['answer']]['score']);
        }
        else{
           $result[$item['answer']]    = array('answer' => $item['answer'], 'score' => $item['score']);
        }
    return $result;
},array()); 

echo "<pre>";
print_r($t);

输出 :

Array
(
    [a] => Array
        (
            [answer] => a
            [score] => 7
        )

    [b] => Array
        (
            [answer] => b
            [score] => 4
        )

    [h] => Array
        (
            [answer] => h
            [score] => 3
        )

)
于 2013-03-26T08:57:30.967 回答
0

我虽然使用了一个临时数组:

/* Current array */
$array = array(
    array("answer" => "a", "score" => 3),
    array("answer" => "b", "score" => 4),
    array("answer" => "h", "score" => 3),
    array("answer" => "a", "score" => 4)
);

/* Using a temporary array */
$tmp_array = array();
foreach($array as $subarray){
    if(array_key_exists($subarray["answer"], $tmp_array)){
        $tmp_array[$subarray["answer"]] += $subarray["score"];
    }else{
        $tmp_array[$subarray["answer"]] = $subarray["score"];
    }
}

/* Creating a new formatted array */
$new_array = array();
foreach($tmp_array as $key => $value){
    $new_array[] = array("answer" => $key, "score" => $value);
}

print_r($new_array);
于 2013-03-26T08:03:11.180 回答