4

I have a multi array that has some duplicated values that are same by name ( name is an element )
i want to sum quantity of each array that has same name , and then unset the second array
Example :

<?php 
 $Array=array(
  0=>array("name"=>"X","QTY"=>500),
  1=>array("name"=>"y","QTY"=>250),
  2=>array("name"=>"X","QTY"=>250)
 );
?>


Now i want to sum duplicated values as below.
Result :

<?php 
 $Array=array(
  0=>array("name"=>"X","QTY"=>750),
  1=>array("name"=>"y","QTY"=>250)
 );
?>

UPDATED
i found this function to search in array , foreach and another loops does not works too

<?php
function search($array, $key, $value)
{
    $results = array();

    if (is_array($array)) {
        if (isset($array[$key]) && $array[$key] == $value) {
            $results[] = $array;
        }

        foreach ($array as $subarray) {
            $results = array_merge($results, search($subarray, $key, $value));
        }
    }

    return $results;
}
?>
LF00
  • 27,015
  • 29
  • 156
  • 295
Nima habibkhoda
  • 253
  • 3
  • 13
  • [`array_reduce()`](http://php.net/manual/en/function.array-reduce.php) is the PHP function you are looking for. – axiac May 14 '17 at 10:33
  • did you try `foreach()`? – RST May 14 '17 at 10:33
  • @RST Updated , foreach does not help . – Nima habibkhoda May 14 '17 at 10:38
  • Did you just add the function or did you actually use it as well? – RST May 14 '17 at 10:40
  • i use it . i am working on codeigniter FrameWork , everything is ok , with this function i can find dupliated values , the main part is sum values and remove another array – Nima habibkhoda May 14 '17 at 10:47
  • @Nimahabibkhoda removing the old array isn't an issue. Just don't use the variable of the old array anymore and the Garbage Collector will remove it. You could also just forcibly `unset` the old variable. – JensV May 14 '17 at 10:48

5 Answers5

1

Try this simplest one, Hope this will be helpful.

Try this code snippet here

$result=array();
foreach ($Array as $value)
{
    if(isset($result[$value["name"]]))
    {
        $result[$value["name"]]["QTY"]+=$value["QTY"];
    }
    else
    {
        $result[$value["name"]]=$value;
    }
}
print_r(array_values($result));
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
1

This problem is a classic example of usage for array_reduce():

$Array = array(
    0 => array('name' => 'X', 'QTY' => 500),
    1 => array('name' => 'y', 'QTY' => 250),
    2 => array('name' => 'X', 'QTY' => 250),
);


// array_values() gets rid of the keys of the array produced by array_reduce()
// they were needed by the callback to easily identify the items in the array during processing
$Array = array_values(array_reduce(
    $Array,
    function (array $a, array $v) {
        $k = $v['name'];
        // Check if another entry having the same name was already processed
        // Keep them in the accumulator indexed by name
        if (! array_key_exists($k, $a)) {
            $a[$k] = $v;        // This is the first entry with this name
        } else {
            // Not the first one; update the quantity
            $a[$k]['QTY'] += $v['QTY'];
        }
        return $a;              // return the partial accumulator
    },
    array()                     // start with an empty array as accumulator
));
axiac
  • 68,258
  • 9
  • 99
  • 134
1
<?php

$Array=array(
0=>array("name"=>"X","QTY"=>500),
1=>array("name"=>"y","QTY"=>250),
2=>array("name"=>"X","QTY"=>250)
);

$result = array();

$names = array_column($Array, 'name');
$QTYs  = array_column($Array, 'QTY');

$unique_names = array_unique($names);

foreach ($unique_names as $name){
    $this_keys = array_keys($names, $name);
    $qty = array_sum(array_intersect_key($QTYs, array_combine($this_keys, $this_keys)));
    $result[] = array("name"=>$name,"QTY"=>$qty);
}

var_export($result); :

array (
  0 => 
  array (
    'name' => 'X',
    'QTY' => 750,
  ),
  1 => 
  array (
    'name' => 'y',
    'QTY' => 250,
  ),
)
Hossam
  • 1,126
  • 8
  • 19
0

You can achieve this by creating an array with name as key and then iterating over all values and add them together, resulting in this

function sum_same($array) {

    $keyArray = [];

    foreach ($array as $entry) {
        $name = $entry["name"];
        if(isset($keyArray[$name])) {
            $keyArray[$name] += $entry["QTY"];
        } else {
            $keyArray[$name] = $entry["QTY"];
        }
    }

    // Convert the keyArray to the old format.
    $resultArray = [];
    foreach ($keyArray as $key => $value) {
        $resultArray[] = ["name" => $key, "QTY" => $value];
    }

    return $resultArray;
}

Try the code here


If you want to alter the old array use the function like this:

$myArray = sum_same($myArray);

The old array will be overwritten by the new one.

JensV
  • 3,997
  • 2
  • 19
  • 43
  • i works but has a problem , i does not remove old array . – Nima habibkhoda May 14 '17 at 10:56
  • @Nimahabibkhoda I updated my answer. If this does what you want then accept my answer, if not please elaborate further what you mean by remove and what you want to achieve by doing that. – JensV May 14 '17 at 10:58
0

Try this, check the live demo.

<?php

$Array=array(
0=>array("name"=>"X","QTY"=>500),
1=>array("name"=>"y","QTY"=>250),
2=>array("name"=>"X","QTY"=>250)
);
$keys = array_column($Array, 'name');
$QTYs = array_column($Array, 'QTY');
$result = [];
foreach($keys as $k => $v)
{
  $result[$v] += $QTYs[$k];
}
print_r($result);
LF00
  • 27,015
  • 29
  • 156
  • 295