多维数组查找和更新的值使用PHP



我找不到合适的标题(帮帮我)。我无法描述这个问题,所以这里是我的问题的例子。

数组:

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分。我真的不知道这个,抱歉我的英语,谢谢你的帮助。请随意评论。:)

$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);

检查这个答案,不使用loop:

$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
        )
)

我想使用一个临时数组:

/* 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);

相关内容

  • 没有找到相关文章

最新更新