兩個陣列中的專案數$newResponse&$key將始終相同$newResponse。$key對于 的每個專案,我想按照預期結果中提到的陣列中$newResponse存在的相同順序添加專案。我怎樣才能做到這一點?$key
dump($newResponse);是一個像下面這樣的陣列,它是foreach回圈的結果。
array:4 [
0 => array:6 [
"courseId" => 18
"courseDisplayName" => "qqq"
]
1 => array:6 [
"courseId" => 1
"courseDisplayName" => "ips"
]
2 => array:6 [
"courseId" => 18
"courseDisplayName" => "qqq"
]
3 => array:6 [
"courseId" => 1
"courseDisplayName" => "ips"
]
]
dump($key);是一個像下面這樣的陣列,它是另一個foreach回圈的結果。
array:4[
0=>[
"totalPoints" => 2
"percent" => 1.0
"id" => 2
]
1=> [
"totalPoints" => 10
"percent" => 2
"id" => 3
]
2=> [
"totalPoints" => 4
"percent" => 0.0
"id" => 6
]
3=> [
"totalPoints" => 4
"percent" => 0.0
"id" => 5
]
]
預期結果:
[
[
"courseId" => 18
"courseDisplayName" => "qqq"
"totalPoints" => 2
"percent" => 1.0
"id" => 2
]
[
"courseId" => 1
"courseDisplayName" => "ips"
"totalPoints" => 10
"percent" => 2
"id" => 3
]
[
"courseId" => 18
"courseDisplayName" => "qqq"
"totalPoints" => 4
"percent" => 0.0
"id" => 6
]
[
"courseId" => 1
"courseDisplayName" => "ips"
"totalPoints" => 4
"percent" => 0.0
"id" => 5
]
]
uj5u.com熱心網友回復:
這是一種方法:
假設您的資料是:
$newResponse = [
[
"courseId" => 18,
"courseDisplayName" => "qqq"
],
[
"courseId" => 1,
"courseDisplayName" => "ips",
],
[
"courseId" => 18,
"courseDisplayName" => "qqq",
],
[
"courseId" => 1,
"courseDisplayName" => "ips",
]
];
$key = [
[
"totalPoints" => 2,
"percent" => 1.0,
"id" => 2
],
[
"totalPoints" => 10,
"percent" => 2,
"id" => 3
],
[
"totalPoints" => 4,
"percent" => 0.0,
"id" => 6
],
[
"totalPoints" => 4,
"percent" => 0.0,
"id" => 5
]
];
然后我可能會使用 array_map,最近將它用于這種目的:
$out = [];
array_map(function($a,$b) use (&$out) {
$out[] = $a $b;
},$newResponse,$key);
print_r($out);
注意上面的 與陣列合并非常相似,我相信在您的用例中可以互換。您可以在此處了解差異:Array_merge 與
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/403873.html
標籤:
