-1

I have the following array which contains 10k records or so

Array
(
    [0] => Array
        (
            [0] => 111
            [1] => 14/02/2020
            [2] => 36
        )

    [6] => Array
        (
            [0] => 222
            [1] => 29/12/2019
            [2] => 1
        )

    [7] => Array
        (
            [0] => 222
            [1] => 27/11/2019
            [2] => 3
        )

    [8] => Array
        (
            [0] => 333
            [1] => 12/09/2019
            [2] => 4
        )

The result I want would be to count how many times each value at [0] occurs along with the sum of what's in [2] to show something like the following

Array
(
    [0] => Array
        (
            [0] => 111
            [1] => 1
            [2] => 36
        )

    [1] => Array
        (
            [0] => 222
            [1] => 2
            [2] => 4
        )

    [2] => Array
        (
            [0] => 333
            [1] => 1
            [2] => 4
        )

I have tried a few things but the code got too unwieldy so I have now come back to a blank piece of paper. I tried array_count_values of a multi dimensional array? which is close as it gives me the count of what is at [0] but seems a bit overkill and I don't get the sum of [2]

1 Answer 1

2
<?php

$entries = [
    [111, '14/02/2020', 36],
    [222, '29/12/2019', 1],
    [222, '27/11/2019', 3],
    [333, '12/09/2019', 4],
];

$results = [];
foreach ($entries as $entry) {
    $results[$entry[0]] = [
        $entry[0],
        ($results[$entry[0]][1] ?? 0) + 1,
        ($results[$entry[0]][2] ?? 0) + $entry[2],
    ];
}
$results = array_values($results);

print_r($results);

or

<?php

$entries = [
    [111, '14/02/2020', 36],
    [222, '29/12/2019', 1],
    [222, '27/11/2019', 3],
    [333, '12/09/2019', 4],
];

$results = [];
foreach ($entries as $entry) {
    if (!isset($results[$entry[0]])) {
        $results[$entry[0]] = [$entry[0], 0, 0];
    }
    ++$results[$entry[0]][1];
    $results[$entry[0]][2] += $entry[2];
}
$results = array_values($results);

print_r($results);
Sign up to request clarification or add additional context in comments.

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.