从子数组中拉取值以填充父数组

时间:2013-10-17 15:03:54

标签: php arrays formatting

我有下面的数组,需要一些额外的结构。

Array
(
[-Others] => Array
    (
        [0] => Array
            (
                [products_sold] => 1
                [products_total_sales] => 2.99
                [products_total_costs] => 1.75
                [products_total_profit] => 1.24
            )

        [1] => Array
            (
                [products_sold] => 1
                [products_total_sales] => 2.3322
                [products_total_costs] => 1.75
                [products_total_profit] => 0.5822
            )

    )

[Addict] => Array
    (
        [0] => Array
            (
                [products_sold] => 1
                [products_total_sales] => 35.1
                [products_total_costs] => 40
                [products_total_profit] => -4.9
            )

显然,我早期就截断了这一点。我想知道是否可以将所有子产品的所有销售额加起来,每个品牌products_total_sales(又名addict

我希望在解析之前得到它,如下所示:

[Addict] => Array
    (
        [0] => Array
        [brand_total_sales] => '$value'
            (
                [products_sold] => 1
                ...

非常感谢任何帮助。提前致谢,随时询问您是否需要更多信息

1 个答案:

答案 0 :(得分:1)

好吧,如果答案是肯定的:

foreach($array as $brand_name => $brand_array) {
    $array[$brand_name]['brand_total_sales'] = 0;

    foreach($brand_array as $product) {
        $array[$brand_name]['brand_total_sales'] += $product['products_total_sales'];
    }
}