2

Problem: Find the sum of the values in 'subtotal' for each 'id' and store the respective sum for each id in an array (or variables).

My sloppy solution at the moment is to run a foreach with multiple if statements inside that count the occurrences. This is adequate for something like 5 ids, but I have to iterate this over 38 ids. I would like to store the results sequentially in an array if possible.

How can I make it more efficient? Any and all help will be appreciated. (See my sloppy solution at the end of this for a good chuckle)

Desired Result:

  • sum of all ID 1 = 10
  • sum of all ID 2 = 18
  • sum of all ID 3 = 14
  • sum of all ID 4 = 4
  • sum of all ID 5 = 3

Array Code for Manipulation

    $someArray = array(

    array(
        'id'=> 1,
        'subtotal'=> 5),
    array(
        'id'=> 1,
        'subtotal'=> 5),
    array(
         'id'=> 2,
         'subtotal'=> 6), 
    array(
         'id'=> 2,
         'subtotal'=> 6),
    array(
         'id'=> 2,
         'subtotal'=> 6),
    array(
         'id'=> 3,
         'subtotal'=> 7),
    array(
         'id'=> 3,
         'subtotal'=> 7),
    array(
         'id'=> 4,
         'subtotal'=> 2),
    array(
         'id'=> 4, 
         'subtotal'=> 2),
    array(
         'id'=> 5,
         'subtotal'=> 3),
    );

Sloppy Solution

$sum_id_1 = 0;
$sum_id_2 = 0;
$sum_id_3 = 0;
$sum_id_4 = 0;
$sum_id_5 = 0;

foreach ($someArray as $k) {

    if ($k['id'] == 1) {
        $sum_id_1 += $k['subtotal'];
    }

    if ($k['id'] == 2) {
        $sum_id_2 += $k['subtotal'];
    }

    if ($k['id'] == 3) {
        $sum_id_3 += $k['subtotal'];
    }

    if ($k['id'] == 4) {
        $sum_id_4 += $k['subtotal'];
    }

    if ($k['id'] == 5) {
        $sum_id_5 += $k['subtotal'];
    }
}

Sloppy Solution Output (on echo)

  • 10
  • 18
  • 14
  • 4
  • 3

2 Answers 2

8
$sum = array_reduce($someArray, function($result, $item) {
    if (!isset($result[$item['id']])) $result[$item['id']] = 0;
    $result[$item['id']] += $item['subtotal'];
    return $result;
}, array());

var_dump($sum); // array(5) { [1]=> int(10) [2]=> int(18) [3]=> int(14) [4]=> int(4) [5]=> int(3) }

For PHP <= 5.3 perform the counting in loop manually:

$sum = array();

foreach ($someArray as $item) {
    if (!isset($sum[$item['id']])) $sum[$item['id']] = 0;
    $sum[$item['id']] += $item['subtotal'];
}
Sign up to request clarification or add additional context in comments.

6 Comments

That was fast! Trying it out as we speak! Edit: Thank you zerkms, I've been wrangling with this for good four hours. Your solution would never have come across my mind. Also if you don't mind me asking, what are some good books to learn the logic necessary to solve problems like this in the future?
@PontusTrade: It would be nice if you upvote and check my answer then (there are arrows on the left and green checkmark sign) ;-)
@PontusTrade zerkms is just scary freaky that way. Makes me rather envious when I see something like this in under a few minutes.
@PontusTrade: I'm not sure about books. I've never read anything specific, it's just about decoupling a task to a smaller. In this case the obvious solution is: loop over each element and calculate subtotal somewhere. That's how you would do that if you do that manually - so you do the same in your code.
@zerkms I meant freaky scary about how fast you provided the answer correctly mate and that I am envious of you being able to code that well and fast :)
|
0
$arr3 = array (
"0" => array ( "001" => 10 ),
"1" => array ( "005" => 20 ),
"2" => array ( "001" => 30 ),
"3" => array ( "003" => 20 ),
"4" => array ( "005" => 80 ),
"5" => array ( "001" => 90 ),
"6" => array ( "003" => 20 ),
"7" => array ( "006" => 80 ),
"8" => array ( "006" => 90 )
) ;

 array (size=4)
   0 => 
      array (size=1)
        '001' => int 130
   1 => 
      array (size=1)
        '005' => int 100
   2 => 
      array (size=1)
       '003' => int 40
   3 => 
      array (size=1)
       '006' => int 170

$outer_array = array();
$unique_array = array();
$inner_array = array();
  foreach($arr3 as $key => $value)
  {

  $item = key($value);
  if(!in_array(key($value), $unique_array))
  {
     array_push($unique_array, $item);
     $inner_array[key($value)] = $value[$item];
     $outer_array[$item][$item] = $value[$item];

  }else{
    $inner_array[key($value)] = $value[$item] + $inner_array[$item];
    $outer_array[$item][$item] = $inner_array[$item];
  }
}
 var_dump(array_values($outer_array));

if you want to sum up all the values with the same key.namely, the above result is what you hope.so my answer is approaching……that is all, wish will help somebody encountering the same situation about this question!

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.