PHP汇总一个数组

时间:2015-07-29 16:12:50

标签: php arrays

我找不到完全相似的问题,所以这里是

给定阵列......

print_r( $givenArray );

将输出:

array (
    [A] => 1
    [B] => 0
    [A] => 3
    [C] => 4
);

我需要对相同键的值求和,因此结果将如下所示

array(
    [A] => 4
    [B] => 0
    [C] => 4
);

怎么可能?感谢

UPD(在ozthgreat评论之后):

[0] => array( 
    [name] => array( 
        [0] => "A", 
        [1] => "B",
        [2] => "C" ) 
    [count] => array( 
        [0] => 1, 
        [1] => 0, 
        [2] => 4 ) ),
[1] => array( 
    [name] => array(
        [0] => "A", 
        [1] => "C") 
    [count] => array(
        [0] => 3, 
        [1] => 4))

原作'数组看起来像这样......更新前的数组看起来很愚蠢,因为我尝试了array_count_valuesarray_combine并且看起来很像

2 个答案:

答案 0 :(得分:1)

/*
You can test with these values:
$givenArray = array(
    array(
        'name' => array('A', 'B', 'C'),
        'count' => array(1, 0, 4),
    ),
    array(
        'name' => array('A', 'C'),
        'count' => array(3, 4),
    )
);
*/

$newArray = array();
// New datas will be put in this new array.

foreach($givenArray as $nameAndCount) {
    foreach($nameAndCount['name'] as $index => $name) {
        if (!isset($newArray[$name])) {
        // Init $newArray[A] for example
            $newArray[$name] = 0;
        }

        $newArray[$name] += $nameAndCount['count'][$index];
        // Add the right 'count' to $newArray[A]
    }
}


/*
Output:
Array
(
    [A] => 4
    [B] => 0
    [C] => 8
)
*/

答案 1 :(得分:-2)

这未经过测试,但请尝试以下方法:

$newArray = array();

foreach ($givenArray as $key => $value){
    // If the array key already exists in the new array
    if(array_key_exists($key,$newArray)){
        // overwrite the element, adding the looped value
        $newArray[$key] = $newArray[$key] + $value; 
    } else {
        // add the element and value to the new array
        $newArray[$key] = $value;
    }
}

var_dump($newArray);