-4

我有这个数组

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
        )

)
4

1 回答 1

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);
于 2012-12-24T12:09:04.267 回答