Q: How to sum values of the array of the same element id 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
        )

)


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

