1

I'm not able to find a solution for the given scenario where I have a multidimensional array in which I have to find the sum of the values of the arrays that have same ID.

demo.php

$array = array("1"=>array("id"=>"1", "total"=>"100"),
                "2"=>array("id"=>"2", "total"=>"300"),
                "3"=>array("id"=>"3", "total"=>"400"),
                 "4"=>array("id"=>"4", "total"=>"500"),
                 "5"=>array("id"=>"1", "total"=>"560"));

I want to get the sum of the total of all the duplicates IDs e.g 1 is the ID and the sum of the total would be 100 + 560 = 650.

1
  • 1
    Just loop through it with a foreach. Commented Aug 28, 2019 at 9:31

4 Answers 4

2

One option is using array_reduce to summarize the array into an associative array.

$array = //....

$result = array_reduce( $array, function( $c, $v ){

    if ( !isset( $c[ $v["id"] ] ) ) $c[ $v["id"] ] = 0;
    $c[ $v["id"] ] += $v["total"];

    return $c;
}, array() ); 

$result will be:

Array
(
    [1] => 660
    [2] => 300
    [3] => 400
    [4] => 500
)

UPDATE

Add another reduce to group the array first. The second reduce is to only include the array elements with more than one count.

$array = //....
$group = array_reduce( $array, function( $c, $v ){
    if ( !isset( $c[ $v["id"] ] ) ) $c[ $v["id"] ] = [ "count" => 0, "total" => 0, "id" => $v["id"] ];
    $c[ $v["id"] ]["count"] += 1;
    $c[ $v["id"] ]["total"] += $v["total"];
    return $c;
}, array() ); 

$result = array_reduce( $group, function( $c, $v ){
    if ( $v["count"] > 1 ) $c[ $v["id"] ] = $v["total"];
    return $c;
}, array() ); 

This will result to:

Array
(
    [1] => 660
)
Sign up to request clarification or add additional context in comments.

1 Comment

result array should not contain other elements . it should contain only the sum of the values of the duplicate id's
2

Another take while using a foreach:

$array = array("1"=>array("id"=>"1", "total"=>"100"),
            "2"=>array("id"=>"2", "total"=>"300"),
            "3"=>array("id"=>"3", "total"=>"400"),
             "4"=>array("id"=>"4", "total"=>"500"),
             "5"=>array("id"=>"1", "total"=>"560"));

$total = [];

foreach ($array as $sub) {
    $total[$sub['id']] = isset($total[$sub['id']]) ? $total[$sub['id']] += $sub['total'] : $total[$sub['id']] = $sub['total'];
}

Output

Array
(
    [1] => 660
    [2] => 300
    [3] => 400
    [4] => 500
)

Live Example

Repl

Reading Material

Ternary Operator

Comments

1

You can use simple foreach loop to get the expected result

<?php
// Your code here!
$array = array("1"=>array("id"=>"1", "total"=>"100"),
                "2"=>array("id"=>"2", "total"=>"300"),
                "3"=>array("id"=>"3", "total"=>"400"),
                 "4"=>array("id"=>"4", "total"=>"500"),
                 "5"=>array("id"=>"1", "total"=>"560"));
$issetArray = array();

foreach ($array as $key => $value) {
    if(isset($issetArray[$value['id']]))
    {
        $issetArray[$value['id']]['total'] += $value['total'];
    }
    else
    {
        $issetArray[$value['id']] = array();
        $issetArray[$value['id']] = $value;
    }
}

$result = array();
foreach ($issetArray as $value) {
    array_push($result, $value);
}

print_r($result);
?>

Example: https://paiza.io/projects/Fnay-hbk4Cuf_-rMTL5AFA

2 Comments

@Script47 You can suggest some point. I'm using the same code in my day by day coding. It would be helpful for me to reduce complicated code. Thanks
Great, Just seen your example from the next time I'll keep the same in mind. Thanks to you learned a new way to do the same thing.
0

If you want to use the external class tableArray and you want to preserve the structure of the input array try this:

$array = array("1"=>array("id"=>"1", "total"=>"100"),
                "2"=>array("id"=>"2", "total"=>"300"),
                "3"=>array("id"=>"3", "total"=>"400"),
                 "4"=>array("id"=>"4", "total"=>"500"),
                 "5"=>array("id"=>"1", "total"=>"560"));

$newData = tableArray::create($array)
  ->filterGroupSum('total',['id'])
  ->fetchAll()
;

$newData:

array (
  0 => 
  array (
    'id' => "1",
    'total' => 660,
  ),
  1 => 
  array (
    'id' => "2",
    'total' => 300,
  ),
  2 => 
  array (
    'id' => "3",
    'total' => 400,
  ),
  3 => 
  array (
    'id' => "4",
    'total' => 500,
  ),
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.