I have two arrays that I want to combine:
Here is the input of my two arrays (notice Factor1 and Factor2 are different, but YearMonth is the same in both arrays):
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
)
)
Here is what I would like the output to be:
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
)
)
I've tried array_merge() but it just appends the second array to the end of the first.
And when I try:
$array3 = [];
foreach (array_merge($array1, $array2) as $row) {
$array3[$row['YearMonth']] = ($array3[$row['YearMonth']] ?? []) + $row;
}
I receive this error:
<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
Any help you can provide is appreciated. Thank you.