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.

 

 

Link to comment
Share on other sites

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

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.