这是我的多维数组:
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),
)
我的预期结果是:
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),
)
口头上,我需要的是在多维数组中找到唯一的object_ids并结合它们的“得分”值。在php中执行此操作的最有效方法是什么?
答案 0 :(得分: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));
这是测试
$ 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));
?>
<强>输出强>
$ 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
)
)