0

I have this array, with these values:

Array
(
[0] => Array
    (
        [0] => 001
        [1] => NAME1
        [2] => 14

    )

[1] => Array
    (
        [0] => 002
        [1] => NAME2
        [2] => 2

    )

[2] => Array
    (
        [0] => 001
        [1] => NAME1
        [2] => 12
}
}

I want export this in csv format but with sum of all value [2] with same number [0]:

Array
(
[0] => Array
    (
        [0] => 001
        [1] => NAME1
        [2] => 26

    )

[1] => Array
    (
        [0] => 002
        [1] => NAME2
        [2] => 2

    )
}
}

I have tried this:

How to sum values of the array of the same element id

but it doesn't work for value [1].

Could you help me, please?

Community
  • 1
  • 1
Leon
  • 141
  • 1
  • 3
  • 13

2 Answers2

0

You could simply loop through your $array array variable.

The idea is to store the $array contents in $result with the key of $result as the nos 001, 002...

We are checking if the key already exists in $result. If it doesn't then we need to add contents of $array. If it exists then we are adding value corresponding to [2].

$result = array();
foreach ($array as $arr) {
    if (!isset($result[$arr[0]])) {
        $result[$arr[0]] = $arr;    /* If key 001, 002... doesn't exist then store $arr content*/
    } else {
        $result[$arr[0]][2] += $arr[2];  /* If key 001, 002... exists then add the value corresponding to [2] and keep the other fields as it is */
    }
}

$result = array_values($result);
Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32
0

Here you are:

$array = array(
    array('001', 'NAME1', 14),
    array('002', 'NAME2', 2),
    array('001', 'NAME1', 12),
);

$result = array();
foreach($array as $k => $v) {
    $id = $v[0];
    $result[$id]['name'] = $v[1];
    $result[$id]['value'][] = $v[2];
}
$new = array();
foreach($result as $key => $value) {
    $new[] = array($key, $value['name'], array_sum($value['value']));
}
echo '<pre>';
print_r($new);

OUTPUT:

Array
(
    [0] => Array
        (
            [0] => 001
            [1] => NAME1
            [2] => 26
        )

    [1] => Array
        (
            [0] => 002
            [1] => NAME2
            [2] => 2
        )

)

You can modify and test the above code here: http://phpio.net/s/129

Manh Nguyen
  • 930
  • 5
  • 12