将相同值数组合并为一个(字符串值)并将其对应的整数值加到同一个索引中?

时间:2012-12-24 11:30:12

标签: php

我有这个数组

Array
(
    [0] => Array
        (
            [category_name] => Dessert1
            [totalOrders] => 3
        )

    [1] => Array
        (
            [category_name] => Dessert1
            [totalOrders] => 1
        )

    [2] => Array
        (
            [category_name] => Category 3
            [totalOrders] => 1
        )

)

我希望将其转换为此数组

Array
(
    [0] => Array
        (
            [category_name] => Dessert1
            [totalOrders] => 4
        )

    [1] => Array
        (
            [category_name] => Category 3
            [totalOrders] => 1
        )

)

1 个答案:

答案 0 :(得分:2)

这真的很简单。您只需循环访问数据并选择唯一的类别即可。如果有重复项,请将订单添加到类别的总数中。

// The stuff from your post
$data = array(
    array('category_name' => 'Dessert1', 'totalOrders' => 3),
    array('category_name' => 'Dessert1', 'totalOrders' => 1),
    array('category_name' => 'Category 3', 'totalOrders' => 1),
);

// Auxiliary variable
$result = array();

// Go over the data one by one
foreach ($data as $item)
{
    // Use the category name to identify unique categories
    $name = $item['category_name'];

    // If the category appears in the auxiliary variable
    if (isset($result[$name]))
    {
        // Then add the orders total to it
        $result[$name]['totalOrders'] += $item['totalOrders'];
    }
    else // Otherwise
    {
        // Add the category to the auxiliary variable
        $result[$name] = $item;
    }
}
// Get the values from the auxiliary variable and override the
// old $data array. This is not strictly necessary, but if you
// want the indices to be numeric and in order then do this.
$data = array_values($result);

// Take a look at the result
var_dump($data);