0

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

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
         )

)

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

谢谢!

4

3 回答 3

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

于 2012-07-24T20:51:44.857 回答
0

您不制作关联数组的任何原因id => count

于 2012-07-24T20:45:11.410 回答
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;
}
于 2012-07-24T20:45:59.753 回答