-1

Here is my multidimensional array :

array(
array('object_id' => 10, 'score' => 1),
array('object_id' => 11, 'score' => 1),
array('object_id' => 12, 'score' => 1),
array('object_id' => 11, 'score' => 1),
array('object_id' => 10, 'score' => 1),
array('object_id' => 14, 'score' => 1),
)

My expected out put is :

array(
    array('object_id' => 10, 'score' => 2),
    array('object_id' => 11, 'score' => 2),
    array('object_id' => 12, 'score' => 1),
    array('object_id' => 14, 'score' => 1),
    )

Verbally, what I need is find the unique object_ids inside the multidimensional array and combine their 'score' value. What is the most efficient way to do this in php?

1

1 Answer 1

1
$output = array();
foreach($array as $e)
{
    if(isset($output[$e['object_id']]))
    {
        $output[$e['object_id']]['score']+=$e['score'];
    }else
    {
        $output[$e['object_id']] = $e;  
    }
}

    print_r(array_values($output));

Here is test

$ cat test.php
<?php

$array = array(
array('object_id' => 10, 'score' => 1),
array('object_id' => 11, 'score' => 1),
array('object_id' => 12, 'score' => 1),
array('object_id' => 11, 'score' => 1),
array('object_id' => 10, 'score' => 1),
array('object_id' => 14, 'score' => 1),
);

$output = array();
foreach($array as $e)
{
    if(isset($output[$e['object_id']]))
    {
        $output[$e['object_id']]['score']+=$e['score'];
    }else
    {
        $output[$e['object_id']] = $e;  
    }
}

// Input
print_r($array);

// Output
print_r(array_values($output));

?>

Output

$ php test.php
Array
(
    [0] => Array
        (
            [object_id] => 10
            [score] => 1
        )

    [1] => Array
        (
            [object_id] => 11
            [score] => 1
        )

    [2] => Array
        (
            [object_id] => 12
            [score] => 1
        )

    [3] => Array
        (
            [object_id] => 11
            [score] => 1
        )

    [4] => Array
        (
            [object_id] => 10
            [score] => 1
        )

    [5] => Array
        (
            [object_id] => 14
            [score] => 1
        )

)
Array
(
    [0] => Array
        (
            [object_id] => 10
            [score] => 2
        )

    [1] => Array
        (
            [object_id] => 11
            [score] => 2
        )

    [2] => Array
        (
            [object_id] => 12
            [score] => 1
        )

    [3] => Array
        (
            [object_id] => 14
            [score] => 1
        )

)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.