1

I have array like this

[
    (int) 0 => [
        'Servloc' => '1',
        'WasteText' => 'Container1',
        'ContainerText' => 'Container Type 1',
        'ContainerCount' => (int) 5,
    ],
    (int) 1 => [
        'Servloc' => '1',
        'WasteText' => 'Container1',
        'ContainerText' => 'Container Type 1',
        'ContainerCount' => (int) 4,
    ],
    (int) 2 => [
        'Servloc' => '1',
        'WasteText' => 'Container1',
        'ContainerText' => 'Container Type 1',
        'ContainerCount' => (int) 3,
    ],
    (int) 3 => [
        'Servloc' => '1',
        'WasteText' => 'Container2',
        'ContainerText' => 'Container Type 1',
        'ContainerCount' => (int) 3,
    ],
    (int) 4 => [
        'Servloc' => '2',
        'WasteText' => 'Container1',
        'ContainerText' => 'Container Type 2',
        'ContainerCount' => (int) 1,
    ],  
]

I need to group this array based on same values of Servloc, WasteText, ContainerText PLUS SUM all values from ContainerCount.

So result for this array should be:

[
    (int) 0 => [
        'Servloc' => '1',
        'WasteText' => 'Container1',
        'ContainerText' => 'Container Type 1',
        'ContainerCount' => (int) 12,
    ],
    (int) 3 => [
        'Servloc' => '1',
        'WasteText' => 'Container2',
        'ContainerText' => 'Container Type 1',
        'ContainerCount' => (int) 3,
    ],
    (int) 4 => [
        'Servloc' => '2',
        'WasteText' => 'Container1',
        'ContainerText' => 'Container Type 2',
        'ContainerCount' => (int) 1,
    ],  
]

I have tried to foreach first array twice and compare those values, if they are same then put in another array as result. But it doesnt work....

1 Answer 1

2

Try this:

function groupArray($data) {
    $keys = array();

    foreach ($data as $child) {
        $key = $child['Servloc'] . $child['WasteText'] . $child['ContainerText'];

        if(!array_key_exists($key, $keys)) {
            // check if we already found objects with the same data, if not then we start with 0 as containercount
            $keys[$key] = array(
                'Servloc' => $child['Servloc'],
                'WasteText' => $child['WasteText'],
                'ContainerText' => $child['ContainerText'],
                'ContainerCount' => 0,
            );
        }

        $keys[$key]['ContainerCount'] += $child['ContainerCount'];
    }

    return array_values($keys);
}
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.