-1

I want sum of the array element ,Which have same element 'Id'. and I want to get new array which does not containing duplicate element 'id'. My array structure is given below.

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
        )

)

I want to get the expected result

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

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



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

)
Muhammed Shuhaib
  • 314
  • 6
  • 20
  • check here `http://stackoverflow.com/questions/1496682/how-to-sum-values-of-the-array-of-the-same-key` – Gowri Dec 01 '14 at 06:02
  • Search yourself before posting any question here. – Jahanzeb Dec 01 '14 at 06:05
  • @Gowri , I dont want whole sum of the array, I want sum of the quantity , When the id's are equal – Muhammed Shuhaib Dec 01 '14 at 06:11
  • 1
    Duplicate: http://stackoverflow.com/questions/19299166/php-array-find-duplicates-sum-them-up-delete-duplicates – Jahanzeb Dec 01 '14 at 06:12
  • @JazyK , I search entire day for this. The above link is not a duplicate for my question. – Muhammed Shuhaib Dec 01 '14 at 06:12
  • @ShuhaibV Its duplicate: you can find you answer here. http://stackoverflow.com/questions/19299166/php-array-find-duplicates-sum-them-up-delete-duplicates – Jahanzeb Dec 01 '14 at 06:14
  • 1
    @ShuhaibV you were searching the entire day??? I just added this line "array value sum and remove duplicate PHP" in google and the first result was the link I posted above. – Jahanzeb Dec 01 '14 at 06:15

1 Answers1

7

Try this one

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

You could also do the following:

<?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);
?>
Manish Jangir
  • 5,329
  • 4
  • 42
  • 75