0

I got the following array:

[0] => Array
    (
        [kanel] => 5
        [peber] => 0
        [shipping] => A
    )

[1] => Array
    (
        [kanel] => 25
        [peber] => 0
        [shipping] => A
    )

[2] => Array
    (
        [kanel] => 25
        [peber] => 0
        [shipping] => C
    )

[3] => Array
    (
        [kanel] => 5
        [peber] => 0
        [shipping] => B
    )

[4] => Array
    (
        [kanel] => 5
        [peber] => 0
        [shipping] => C
    )

I want to print the following:

A Kanel: 30 Peber: 0

B Kanel: 5 Peber: 0

C Kanel: 30 Peber: 0

Literally grouping on shipping, sum on kanel and sum on peber as well. I can find a lot on how to do it with one column, but it doesn't do the trick. :)

Thank you!

1 Answer 1

1

To group and sum the values in your array by the shipping field, you can use a loop and a temporary associative array to store the intermediate results. Here is an example of how you can do this:

$result = array();

foreach ($array as $item) {
  $shipping = $item['shipping'];
  if (!isset($result[$shipping])) {
    $result[$shipping] = array(
      'kanel' => 0,
      'peber' => 0,
    );
  }
  $result[$shipping]['kanel'] += $item['kanel'];
  $result[$shipping]['peber'] += $item['peber'];
}

// Print the results
foreach ($result as $shipping => $values) {
  echo $shipping . ' Kanel: ' . $values['kanel'] . ' Peber: ' . $values['peber'] . "\n";
}

This will produce the following output:

A Kanel: 30 Peber: 0
B Kanel: 5 Peber: 0
C Kanel: 30 Peber: 0
1
  • 1
    Thank you, it did the trick flawless!
    – Jannickla
    Jan 8 at 22:13

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.