0 レビュー
1 回答
PHPは、2つの配列を1つに結合し、共通のIDをテキストとして使用します
組み合わせたいアレイが2つあります:
これが私の2つの配列の入力です( Factor1
とFactor2
は異なりますが、 {-code -3}
は両方のアレイで同じです):
配列
((
[0]=>stdClassオブジェクト
((
[YearMonth] => 2022-01
[Factor1] => 627
)。
[1]=>stdClassオブジェクト
((
[YearMonth] => 2021-12
[Factor1] => 3006
)。
[2]=>stdClassオブジェクト
((
[YearMonth] => 2021-11
[Factor1] => 2456
)。
[3]=>stdClassオブジェクト
((
[YearMonth] => 2021-10
[Factor1] => 1482
)。
[4]=>stdClassオブジェクト
((
[YearMonth] => 2021-09
[Factor1] => 1266
)。
[5]=>stdClassオブジェクト
((
[YearMonth] => 2021-08
[Factor1] => 1981
)。
)。
配列
((
[0]=>stdClassオブジェクト
((
[YearMonth] => 2022-01
[Factor2] => 380
)。
[1]=>stdClassオブジェクト
((
[YearMonth] => 2021-12
[Factor2] => 1773
)。
[2]=>stdClassオブジェクト
((
[YearMonth] => 2021-11
[Factor2] => 769
)。
[3]=>stdClassオブジェクト
((
[YearMonth] => 2021-10
[Factor2] => 700
)。
[4]=>stdClassオブジェクト
((
[YearMonth] => 2021-09
[Factor2] => 608
)。
[5]=>stdClassオブジェクト
((
[YearMonth] => 2021-08
[Factor2] => 859
)。
)。
出力は次のようになります。
配列
((
[0]=>stdClassオブジェクト
((
[YearMonth] => 2022-01
[Factor1] => 627
[Factor2] => 380
)。
[1]=>stdClassオブジェクト
((
[YearMonth] => 2021-12
[Factor1] => 3006
[Factor2] => 1773
)。
[2]=>stdClassオブジェクト
((
[YearMonth] => 2021-11
[Factor1] => 2456
[Factor2] => 769
)。
[3]=>stdClassオブジェクト
((
[YearMonth] => 2021-10
[Factor1] => 1482
[Factor2] => 700
)。
[4]=>stdClassオブジェクト
((
[YearMonth] => 2021-09
[Factor1] => 1266
[Factor2] => 608
)。
[5]=>stdClassオブジェクト
((
[YearMonth] => 2021-08
[Factor1] => 1981
[Factor2] => 859
)。
)。
array_merge()
を試しましたが、最初の配列の最後に2番目の配列を追加するだけです。
そして試してみると:
$ 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
ご協力いただければ幸いです。ありがとうございます。
わからない
0
レビュー
答え :
解決策:
次のような方法を試してください
// 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
}
わからない
同様の質問
私たちのウェブサイトで同様の質問で答えを見つけてください。