foreach 循环和 array_merge 不正确匹配

foreach loop and array_merge not matching correctly

我有以下两个数组,我正试图将它们合并到一个找到共同 order_id 的数组中:

$订单数组:

[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 returns 一个从 0 开始进行数字索引的数组,不管 键输入数组的。因此,如果输入数组也不是从 0 开始进行数字索引,则 array_search 返回的键不一定与输入数组中的键匹配(这就是为什么您的代码根本不会 运行您问题中的示例数据)。解决这个问题的最简单方法是 re-index $chitchattracking by 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
        )
)

Demo on 3v4l.org