php嵌套foreach意外结果

时间:2018-06-08 23:34:01

标签: php multidimensional-array foreach

我不太明白发生了什么。复制以下代码并运行它你应该看到我所看到的。

$stores = array(
        (object)[
            "store_id" => 1,
        ],
        (object)[
            "store_id" => 2,
        ],
        (object)[
            "store_id" => 3,
        ]
    );

    $currentYear = date('Y');
    $monthes = array();
    for($i = 1; $i <= 4; $i++){
        $temp = new stdClass();
        $temp->month = $i;
        $temp->sales = 0;
        array_push($monthes, $temp);
    }
    foreach($stores as $store){
        $store->sales = array(
            "currentYear" => (object)[
                "year" => $currentYear,
                "monthes" => $monthes,
            ],
        );
    }

    foreach($stores as $store){
        foreach($store->sales as $year){
           foreach($year->monthes as $month){
               $month->sales += 1;
           }
        }
    }

    print_r("<pre>"); 
    print_r($stores);
    print_r("</pre>");

它产生的结果如下所示:

   Array
    (
        [0] => stdClass Object
            (
                [store_id] => 1
                [sales] => Array
                    (
                        [currentYear] => stdClass Object
                            (
                                [year] => 2018
                                [monthes] => Array
                                    (
                                        [0] => stdClass Object
                                            (
                                                [month] => 1
                                                [sales] => 3
                                            )

                                        [1] => stdClass Object
                                            (
                                                [month] => 2
                                                [sales] => 3
                                            )

但是我期待销售额为1.而不是3.因为看起来它每个月只会访问一次而销售额的初始值为0.所以0 + = 1应该只是1.看起来好像,它循环了3次。

我无法解决我在这里做错了什么。

1 个答案:

答案 0 :(得分:2)

您将相同的$monthes数组存储到每个currentYear对象中。在分配数组时复制数组,但它包含的对象不是;所有这些数组都包含对相同四个对象的引用。因此,当您在商店1个月1中增加销售额时,它还会增加商店2个月1,商店3个月1,商店4个月1。

您需要将创建$monthes数组的循环放在填充每个商店的循环中。

<?php
$stores = array(
    (object)[
        "store_id" => 1,
        ],
    (object)[
        "store_id" => 2,
        ],
    (object)[
        "store_id" => 3,
        ]
    );

$currentYear = date('Y');
foreach($stores as $store){
    $monthes = array();
    for($i = 1; $i <= 4; $i++){
        $temp = new stdClass();
        $temp->month = $i;
        $temp->sales = 0;
        array_push($monthes, $temp);
    }
    $store->sales = array(
        "currentYear" => (object)[
            "year" => $currentYear,
            "monthes" => $monthes,
            ],
        );
}

foreach($stores as $store){
    foreach($store->sales as $year){
        foreach($year->monthes as $month){
            $month->sales += 1;
        }
    }
}

echo "<pre>";
print_r($stores);
echo "</pre>";