Jump to content

Removing duplicates and adding up their values in multidimentional arrays


bachx

Recommended Posts

I'm looking for a way to remove duplicate values from the following example and add up their sum in a way like this:

 

Array
(
    [0] => Array
        (
            [name] => CAR
            [amount] => 1000
        )

    [1] => Array
        (
            [name] => BUS
            [amount] => 500
        )

    [2] => Array
        (
            [name] => CAR
            [amount] => 750
        )

)

 

To:

 

Array
(
    [0] => Array
        (
            [name] => CAR
            [amount] => 1750
        )

    [1] => Array
        (
            [name] => BUS
            [amount] => 500
        )


)

 

Any ideas? Thanks.

 

 

<?php
$array1 = array(array('name'=>'CAR', 'amount'=>1000), array('name'=>'BUS', 'amount'=>500), array('name'=>'CAR', 'amount'=>750));

$array2 = array();

foreach($array1 as $miniarray)
{
if(isset($array2[$miniarray['name']]))
{
	$array2[$miniarray['name']] += $miniarray['amount'];
}	
else
{
	$array2[$miniarray['name']] = $miniarray['amount'];
}
}

//if it has to be in the format you specified
$array1 = array();
foreach($array2 as $key=>$value)
{
$array1[] = array($key=>$value);
}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.