[英]foreach loop and array_merge not matching correctly
我有以下兩個數組,我試圖將它們合並到一個找到公共 order_id 的數組中:
$orders 數組:
[0] => Array (
[order_id] => 45145
[customers_email_address] => test@test.com
[customers_name] => test name
)
[1] => Array (
[order_id] => 45136
[customers_email_address] => test@yahoo.com
[customers_name] => test name
)
[2] => Array (
[order_id] => 45117
[customers_email_address] => test@yahoo.com
[customers_name] => test name
)
[3] => Array (
[order_id] => 44959
[customers_email_address] => test@gmail.com
[customers_name] => test name
)
[4] => Array (
[order_id] => 44938
[customers_email_address] => test@hotmail.com
[customers_name] => t
)
$chitchattracking 數組:
[1] => Array (
[order_id] => 44938
[carrier_tracking_code] => 9205590221582717655498
)
[2] => Array (
[order_id] => 44854
[carrier_tracking_code] => 92055902215827
)
在上面的數組樣本中有一個 order_id 匹配:44938
這是我檢查匹配的代碼,並將其放入新數組 $tracked 中:
foreach ($orders as $order) {
if (($key = array_search($order['order_id'], array_column($chitchattracking, 'order_id'))) !== false) {
$tracked[] = array_merge( $order, $chitchattracking[$key]);
}
}
不知何故,我真的把它搞砸了,它匹配了錯誤的 order_ids 並發布了不正確的跟蹤號碼。 此外,當我以有限的數量運行代碼時,它甚至找不到匹配項。
您的問題幾乎肯定是由array_column
返回一個從 0 開始數字索引的數組的事實引起的,而不管輸入數組的鍵是什么。 因此,如果輸入數組的數字索引也不是從 0 開始,則array_search
返回的鍵不一定與輸入數組中的鍵匹配(這就是為什么您的代碼根本不會使用問題中的示例數據運行的原因)。 解決此問題的最簡單方法是通過order_id
重新索引$chitchattracking
order_id
,然后您可以進行簡單的isset
檢查以控制對$tracking
的推送:
$tracking = array();
$chitchat = array_column($chitchattracking, null, 'order_id');
foreach ($orders as $order) {
$order_id = $order['order_id'];
if (isset($chitchat[$order_id])) {
$tracking[] = array_merge($order, $chitchat[$order_id]);
}
}
print_r($tracking);
輸出:
Array
(
[0] => Array
(
[order_id] => 44938
[customers_email_address] => test@hotmail.com
[customers_name] => t
[carrier_tracking_code] => 9.2055902215827E+21
)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.