我不太明白发生了什么。复制以下代码并运行它,您应该会看到我所看到的内容。
$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次。
我不能回想我在这里做错了什么。
发布于 2018-06-09 07:45:54
您将在每个currentYear
对象中存储相同的$monthes
数组。虽然在分配数组时会复制该数组,但它包含的对象不会复制;所有这些数组都包含对相同四个对象的引用。因此,当您在商店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>";
https://stackoverflow.com/questions/50769600
复制相似问题