php嵌套foreach意外结果
我不太明白发生了什么事。复制以下代码并运行它,您应该可以看到我看到的内容php嵌套foreach意外结果,php,multidimensional-array,foreach,Php,Multidimensional Array,Foreach,我不太明白发生了什么事。复制以下代码并运行它,您应该可以看到我看到的内容 $stores = array( (object)[ "store_id" => 1, ], (object)[ "store_id" => 2, ], (object)[ "store_id" => 3, ] ); $c
$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>");
但我预计销售额将是1。而不是3。因为它看起来每个月只访问1次,销售的初始值为0。所以0+=1应该是1。看起来好像它自己绕了三圈
我不能对我在这里做错的事耿耿于怀 您正在将相同的
$monthes
数组存储到每个currentYear
对象中。当您指定阵列时,阵列会被复制,但阵列中包含的对象不会被复制;所有这些数组都包含对相同四个对象的引用。因此,当您增加门店1个月1的销售额时,它也会增加门店2个月1、门店3个月1和门店4个月1的销售额
您需要将创建$monthes
数组的循环放入填充每个存储的循环中
您正在将相同的$monthes
数组存储到每个currentYear
对象中。当您指定阵列时,阵列会被复制,但阵列中包含的对象不会被复制;所有这些数组都包含对相同四个对象的引用。因此,当您增加门店1个月1的销售额时,它也会增加门店2个月1、门店3个月1和门店4个月1的销售额
您需要将创建$monthes
数组的循环放入填充每个存储的循环中
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
)
<?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>";