如何求和相同元素id的数组的值

时间:2014-12-01 05:58:52

标签: php arrays

我想要数组元素的总和,它具有相同的元素'Id'。 我想获得不包含重复元素'id'的新数组。 我的数组结构如下所示。

Array
(
    [0] => Array
        (
            [id] => 693
            [quantity] => 40
        )

    [1] => Array
        (
            [id] => 697
            [quantity] => 10
        )

    [2] => Array
        (
            [id] => 693
            [quantity] => 20
        )

    [3] => Array
        (
            [id] => 705
            [quantity] => 40
        )

)

我想得到预期的结果

Array
(
    [0] => Array
        (
            [id] => 693
            [quantity] => 60
        )

    [1] => Array
        (
            [id] => 697
            [quantity] => 10
        )



    [2] => Array
        (
            [id] => 705
            [quantity] => 40
        )

)

1 个答案:

答案 0 :(得分:4)

试试这个

<?php 
$array = array(
        array('id' => 693, 'quantity' => 40),
        array('id' => 697, 'quantity' => 10),
        array('id' => 693, 'quantity' => 20),
        array('id' => 705, 'quantity' => 40),
        );

$result = array();
foreach($array as $k => $v) {
    $id = $v['id'];
    $result[$id][] = $v['quantity'];
}

$new = array();
foreach($result as $key => $value) {
    $new[] = array('id' => $key, 'quanity' => array_sum($value));
}
echo '<pre>';
print_r($new);
?>

您还可以执行以下操作:

<?php
$final = array();
foreach($array as $value) {
    $id = $value['id'];
    $filter = array_filter($array, function($ar) {
        GLOBAL $id;
        $valueArr = ($ar['id'] == $id);
        return $valueArr;
    });
    $sum = array_sum(array_column($filter, 'quantity'));
    $final[$id] = array('id' => $id, 'quantity' => $sum);
}
echo '<pre>';
print_r($final);
?>