場景:如果匹配,則用PHP中另一個數組的值替換數組中的值。多維數組
我有這2個數組:
array1
:
Array
(
[1] => Array
(
[label] => pending
[fillColor] => #468847
[data] => 50
)
[2] => Array
(
[label] => dispatched
[fillColor] => #6ecf70
[data] => 10
)
[3] => Array
(
[label] => delivered
[fillColor] => #f89406
[data] => 1
)
[4] => Array
(
[label] => invoiced
[fillColor] => #3a87ad
[data] => 2
)
)
array2
:
Array
(
[1] => Array
(
[label] => pending
[fillColor] => #468847
[data] => Array
(
[0] => 1
)
)
)
我需要的結果是
Array
(
[1] => Array
(
[label] => pending
[fillColor] => #468847
[data] => Array
(
[0] => 50
[1] => 1
)
)
[2] => Array
(
[label] => dispatched
[fillColor] => #6ecf70
[data] => Array
(
[0] => 10
[1] => 0
)
)
[3] => Array
(
[label] => delivered
[fillColor] => #f89406
[data] => Array
(
[0] => 1
[1] => 0
)
)
[4] => Array
(
[label] => invoiced
[fillColor] => #3a87ad
[data] => Array
(
[0] => 2
[1] => 0
)
)
)
只有4個標籤:
pending
dispatched
delivered
invoiced
請注意,數組只是一個例子。可能發生的情況是,第一個數組根本沒有值,或者只有2個,第二個數組有3個值或沒有值。
因爲那上面的約束,我想用array_replace
並具有陣列的所謂
base_array = ["pending", "dispatched", "delivered", "invoiced"]
我試圖環路base_array
和嘗試,如果標籤存在於array1
與array2
匹配。
基本上,如果鍵(這是標記)不以任何的array1
或array2
然後存在替換的值將所得數組中爲0。
我已經試過
foreach($base_array as $key => $value) {
if(in_array($key, $array1[$key])) {
$array[$key] = $array1[$key];
}
}
,但它看起來像我失去了對這些多維數組和更換。任何幫助將非常感激。謝謝。
你能解釋一下你的結果陣列數據的關鍵?你的預期結果是什麼? – rocky
期望的數組結果在上面。謝謝。 –
謝謝你的時間。我已經重寫了SQL查詢並返回更好的數組。 –