我有兩個要組合的陣列:
這是我的兩個陣列的輸入(注意Factor1和Factor2不同,但YearMonth在兩個陣列中是相同的):
Array
(
[0] => stdClass Object
(
[YearMonth] => 2022-01
[Factor1] => 627
)
[1] => stdClass Object
(
[YearMonth] => 2021-12
[Factor1] => 3006
)
[2] => stdClass Object
(
[YearMonth] => 2021-11
[Factor1] => 2456
)
[3] => stdClass Object
(
[YearMonth] => 2021-10
[Factor1] => 1482
)
[4] => stdClass Object
(
[YearMonth] => 2021-09
[Factor1] => 1266
)
[5] => stdClass Object
(
[YearMonth] => 2021-08
[Factor1] => 1981
)
)
Array
(
[0] => stdClass Object
(
[YearMonth] => 2022-01
[Factor2] => 380
)
[1] => stdClass Object
(
[YearMonth] => 2021-12
[Factor2] => 1773
)
[2] => stdClass Object
(
[YearMonth] => 2021-11
[Factor2] => 769
)
[3] => stdClass Object
(
[YearMonth] => 2021-10
[Factor2] => 700
)
[4] => stdClass Object
(
[YearMonth] => 2021-09
[Factor2] => 608
)
[5] => stdClass Object
(
[YearMonth] => 2021-08
[Factor2] => 859
)
)
這是我希望輸出的內容:
Array
(
[0] => stdClass Object
(
[YearMonth] => 2022-01
[Factor1] => 627
[Factor2] => 380
)
[1] => stdClass Object
(
[YearMonth] => 2021-12
[Factor1] => 3006
[Factor2] => 1773
)
[2] => stdClass Object
(
[YearMonth] => 2021-11
[Factor1] => 2456
[Factor2] => 769
)
[3] => stdClass Object
(
[YearMonth] => 2021-10
[Factor1] => 1482
[Factor2] => 700
)
[4] => stdClass Object
(
[YearMonth] => 2021-09
[Factor1] => 1266
[Factor2] => 608
)
[5] => stdClass Object
(
[YearMonth] => 2021-08
[Factor1] => 1981
[Factor2] => 859
)
)
我已經嘗試過,array_merge()但它只是將第二個陣列附加到第一個陣列的末尾。
當我嘗試時:
$array3 = [];
foreach (array_merge($array1, $array2) as $row) {
$array3[$row['YearMonth']] = ($array3[$row['YearMonth']] ?? []) $row;
}
我收到此錯誤:
<b>Fatal error</b>: Uncaught Error: Cannot use object of type stdClass as array in /var/www/html/wp-content/plugins/ad-inserter-pro/class.php(606) : eval()'d code:23
感謝您提供的任何幫助。謝謝你。
uj5u.com熱心網友回復:
嘗試這樣的事情
// loop thru 1st array using & to treat value as a reference, so that we can modify values in that array
foreach ($array1 as &$value) {
// loop through 2nd array
foreach ($array2 as $value2) {
// look for matching YearMonth (use -> because they are objects)
if ($value->YearMonth === $value2->YearMonth) {
// when a match is found, copy the Factor2 value
$value->Factor2 = $value2->Factor2
// for efficiency exit the 2nd loop, because there is no point checking any more rows if we have already found the match
break;
}
}
// after exiting the 2nd loop, code will carry on here, and keep checking values in the 1st loop
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/405954.html
標籤:
下一篇:用變數創建陣列
