通过删除相同的键值来简化数组

时间:2014-09-24 05:31:07

标签: php arrays multidimensional-array key key-value

我有一个像这样的数组

Array
(
    [0] => Array
        (
            [vendor_id] => 2
            [vendor_total_order] => 80
        )

    [1] => Array
        (
            [vendor_id] => 2
            [vendor_total_order] => 100
        )

    [2] => Array
        (
            [vendor_id] => 1
            [vendor_total_order] => 150
        )
    [3] => Array
        (
            [vendor_id] => 3
            [vendor_total_order] => 80
        )

    [4] => Array
        (
            [vendor_id] => 5
            [vendor_total_order] => 150
        )

    [5] => Array
        (
            [vendor_id] => 1
            [vendor_total_order] => 110
        )

)

我想以这样一种方式简化这个数组,如果' vendor_id'两个值相同,那里累积/总和值应分配给'vendor_total_order'到那个' vendor_id'(基本上我们正在删除具有相同vendor_id的值与重复项的总值)。

因此,当我提供上述数组作为输入时,输出应如下所示

Array
(
    [0] => Array
        (
            [vendor_id] => 2
            [vendor_total_order] => 180
        )

    [1] => Array
        (
            [vendor_id] => 1
            [vendor_total_order] => 260
        )
    [2] => Array
        (
            [vendor_id] => 3
            [vendor_total_order] => 80
        )

    [3] => Array
        (
            [vendor_id] => 5
            [vendor_total_order] => 150
        )

)

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您只需要使用foreach对它们进行分组。例如:

$total = array();
foreach ($array as $key => $value) {
    if(!isset($total[$value['vendor_id']])) {
        $total[$value['vendor_id']] = array('vendor_id' => $value['vendor_id'], 'vendor_total_order' => 0);
    }
    $total[$value['vendor_id']]['vendor_total_order'] += $value['vendor_total_order'];
}

$total = array_values($total); // simple reindex
echo '<pre>';
print_r($total);

Sample Output

答案 1 :(得分:0)

最好的办法是编写一个执行以下操作的自定义脚本:

  1. 创建一个空的新“结果”数组
  2. 迭代当前数组和每个项目:
  3. 如果结果中不存在该项,请插入该项,否则将total_value值更新为其当前值与新项的总和。
  4. 保存结果数组