tags:

views:

44

answers:

1

I have an array that looks like the following:

Array (

[0] => Array
    (
        [id] => 10
        [value] => 5
    )

[1] => Array
    (
        [id] => 10
        [value] => 1
    )

[2] => Array
    (
        [id] => 11
        [value] => 1
    )

[3] => Array
    (
        [id] => 11
        [value] => 1
    )

)

How can I consolidated the array by id? The resulting array I'm looking for would be something like:

Array (

[0] => Array
    (
        [id] => 10
        [value] => 6
    )

[1] => Array
    (
        [id] => 11
        [value] => 2
    )

)

+2  A: 

This is not a very efficient structure. Have you considered consolidating it in this form?

array
(
    10 => 6,
    11 => 2,
);

That would allow fast key lookup on ID.

TO consolidate your first array into that form, just do this:

$array2 = array();
foreach($array1 as $row)
{
    if(isset($array2[$row['id']]))
        $array2[$row['id']] += $row['value'];
    else
        $array2[$row['id']] = $row['value'];
}

Which would give you an array in the form of:

$array2 = array
(
    10 => 6,
    11 => 2,
);

If you really need it in your requested form, one more processing loop will get it there...

$array3 = array();
foreach($array2 as $id => $value)
{
    $array3[] = array('id' => $id, 'value' => $value);
}

So, there you go!


And more compact:

$array2 = array();
foreach($array1 as $row)
    $array2[$row['id']] = (isset($array2[$row['id']]) ? $array2[$row['id']] : 0) + $row['value'];

$array3 = array();
foreach($array2 as $id => $value)
    $array3[] = array('id' => $id, 'value' => $value);
gahooa