-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 に答える