在数组中添加值,其中id是相同的php

时间:2013-04-19 08:39:46

标签: php arrays

我有一个数组。在数组中有2个[id]值相同。 我希望能够添加这些元素的[得分]并合并[id]相同的元素。这可能吗?

[0] =>  
        [id] => 9428 
        [auth] => manual 
        [firstname] => Tariq 
        [lastname] => Essop 
        [score] => 75.000000000 
        [timecreated] => 1366093740 
        [courseid] => 215 
        [itemname] => 2164 Date of assessment and dispute resolution 
        [itemid] => 750 ) 

[1] => 
        [id] => 9428 
        [auth] => manual 
        [firstname] => Tariq 
        [lastname] => Essop 
        [score] => 75.000000000 
        [timecreated] => 1366100428 
        [courseid] => 215 
        [itemname] => 2168 Cross-border loans and intellectual property 
        [itemid] => 751 )

[2] => 
        [id] => 6258 
        [auth] => manual 
        [firstname] => Tariq 
        [lastname] => Essop 
        [score] => 75.000000000 
        [timecreated] => 1366100428 
        [courseid] => 215 
        [itemname] => 2168 Cross-border loans and intellectual property 
        [itemid] => 752 )

1 个答案:

答案 0 :(得分:1)

$data = array();

foreach ($array as $item) {
    if (!isset($data[$item['id']])) {
        $data[$item['id']] = $item;
    } else {
        // do whatever you need to do to $data[$item['id']], e.g.:
        $data[$item['id']]['score'] += $item['score'];
    }
}