-1

I'm trying to convert an array, to one where specific values are summed up 'distincted' on another value.

Let me be specific:

Array
(
    [0] => stdClass Object
        (
            [id_space] => LIVING
            [running_meters] => 4.22
        )

    [1] => stdClass Object
        (
            [id_space] => LIVING
            [running_meters] => 9.69
        )

    [2] => stdClass Object
        (
            [id_space] => LIVING
            [running_meters] => 32.79
        )

    [3] => stdClass Object
        (
            [id_space] => KITCHEN
            [running_meters] => 30.34
        )

    [4] => stdClass Object
        (
            [id_space] => KITCHEN
            [running_meters] => 22.83
        )

    [5] => stdClass Object
        (
            [id_space] => KITCHEN
            [running_meters] => 24.00
        )

    [6] => stdClass Object
        (
            [id_space] => HALL
            [running_meters] => 5.83
        )

    [7] => stdClass Object
        (
            [id_space] => HALL
            [running_meters] => 21.81
        )

)

Converted to:

Array
(
    [0] => stdClass Object
        (
            [id_space] => LIVING
            [running_meters] => 46.7
        )

    [1] => stdClass Object
        (
            [id_space] => KITCHEN
            [running_meters] => 53,17
        )

    [2] => stdClass Object
        (
            [id_space] => HALL
            [running_meters] => 24.00
        )       

)


So I get the sum of the running_meters of each 'space'.

Thanks in advance, appreciate it.

I think searched all related questions here on the onlines, but all of them counted number of items in an array, not the sum of the values.

  • 5
    What have you tried? Show us your best attempt (code). – lovelace Sep 17 '19 at 08:21
  • We are here to help, but not to solve problems for you. Show us your code. What did you try so far? – MilanG Sep 17 '19 at 08:28
  • I'm sort of a newbie in this space and understand your comment: I tried a bunch of examples I found online, but guess I need to do more extensive research and writing more own code next time. Also, I didn't found https://stackoverflow.com/questions/5269188/php-group-by-sum-using-multi-dimensional-array :s – Joris Lucius Sep 17 '19 at 09:35

1 Answers1

0

You can traverse you array and sum the result, check the Demo

$result = [];
foreach ($array as $v) {
    $id_space = $v->id_space;
    if (isset($result[$id_space]) === true) {
        $result[$id_space]->running_meters += $v->running_meters;
    } else {
        $result[$id_space] = new stdClass();
        $result[$id_space]->id_space = $id_space;
        $result[$id_space]->running_meters = $v->running_meters;
    }
}

$result = array_values($result);
var_dump($result);
LF00
  • 27,015
  • 29
  • 156
  • 295