PHP基于特定元素的值组合数组

时间:2012-07-24 20:35:26

标签: php arrays

我有一个看起来像这样的数组

Array ( 

[0] => Array
        (
            [id] => 123
            [count] => 1
        )

    [1] => Array
        (
            [id] => 123
            [count] => 3
        )

    [2] => Array
        (
            [id] => 513
            [count] => 0
        )
    [3] => Array
        (
             [id] => 561
             [count] => 1
         )
     [4] => Array
         (
              [id] => 613
              [count] => 7
         )

)

我想要做的是创建一个新数组,它总计id值相同的计数。例如,新数组看起来像这样:

Array ( 

[0] => Array
        (
            [id] => 123
            [count] => 4
        )

    [1] => Array
        (
            [id] => 513
            [count] => 0
        )
    [2] => Array
        (
             [id] => 561
             [count] => 1
         )
     [3] => Array
         (
              [id] => 613
              [count] => 7
         )

)

有人知道这样做的好方法吗?

谢谢!

3 个答案:

答案 0 :(得分:0)

您没有制作id => count

的关联数组的任何原因

答案 1 :(得分:0)

您可以使用以下函数执行此操作(我没有测试代码,但它应该可以工作):

function get_count_array($arr) {
    $new_array = array(); 

    foreach($arr as $item) {
        $found = false;

        //loop through all the current new items to check if we already have it
        for($i = 0; $i < count($new_array); $i++) {
            //do we have it?
            if($new_array[$i]['id'] == $item['id']) { 
                $new_array[$i]['count'] += 1;
                $found = true;

                break;
            }
        }

        if(!$found) {
            $new_array[] = array('id' => $item['id'], 'count' => 0);
        }
    }

    return $new_array;
}

答案 2 :(得分:0)

简短而简单:

$new_array = array();

foreach($data_array as $value) {
    if(array_key_exists($value['id'], $new_array)) {
        $new_array[$value['id']] += $value['count'];
    } else {
        $new_array[$value['id']] = $value['count'];
    }
}

echo print_r($new_array,true);

我将其设为id => value,因为当id可用作数组的密钥时,似乎不需要另一个数据数组。