PHP 嵌套为每个意外结果



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

$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。 因为它看起来每个月只会访问 1 次,而销售额的初始值为 0。所以 0 += 1 应该只是 1。看起来好像,它绕了 3 次。

我无法思考我在这里做错了什么。

您将相同的$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>";

最新更新