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

)
7
  • check here http://stackoverflow.com/questions/1496682/how-to-sum-values-of-the-array-of-the-same-key Commented Dec 1, 2014 at 6:02
  • Search yourself before posting any question here. Commented Dec 1, 2014 at 6:05
  • @Gowri , I dont want whole sum of the array, I want sum of the quantity , When the id's are equal Commented Dec 1, 2014 at 6:11
  • 1
    Duplicate: stackoverflow.com/questions/19299166/… Commented Dec 1, 2014 at 6:12
  • 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. Commented Dec 1, 2014 at 6:15

1 Answer 1

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);
?>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.