gpt4 book ai didi

php - 将第一个数组的特定键和值合并到第二个数组中

转载 作者:可可西里 更新时间:2023-11-01 00:28:29 26 4
gpt4 key购买 nike

我有两个数组

$arr1 = Array ( 
[0] => Array ( [customer_id] => 1 [Expire] => 2019-05-14 [paid] => 1 )
[1] => Array ( [customer_id] => 2 [Expire] => 2019-06-20 [paid] => 0 ))

$arr2 = Array ( 
[0] => Array ( [id] => 3943 [customer_id] => 1 [Expire] => 2019-05-14 )
[1] => Array ( [id] => 3944 [customer_id] => 1[Expire] => 2019-05-14 )
[2] => Array ( [id] => 4713 [customer_id] => 2 [Expire] => 2019-06-20 )
)

如果客户 ID 和过期匹配,则尝试将第一个数组键和值 [paid]=>1 或 0 放入第二个数组中

Array ( 
[0] => Array ( [id] => 3943 [customer_id] => 1 [Expire] => 2019-05-14 [paid] => 1)
[1] => Array ( [id] => 3944 [customer_id] => 1 [Expire] => 2019-05-14 [paid] => 1)
[2] => Array ( [id] => 4713 [customer_id] => 2 [Expire] => 2019-06-20 [paid] => 0)
)

我尝试在 php 中合并数组,但没有得到我想要的。是否有任何 php 函数可以做到这一点?

最佳答案

循环第二个数组 $arr2,找到第一个数组 $arr1 的索引,其中列 customer_id$arr2 的当前迭代。 array_search() 返回该索引,然后我们可以使用它来获取该数组的 paid 索引。然后我们通过执行 $a['paid'] = $paid; 将它附加到我们的数组 $arr2

由于我们通过引用(循环中$a 之前的&)循环数组,我们对它所做的更改将被应用回原始数组。

foreach ($arr2 as &$a) {
$customerID = $a['customer_id']; // This customer ID
$arr1_key = array_search($customerID, array_column($arr1, 'customer_id')); // Find the index of this customerID in the first array
$paid = $arr1[$arr1_key]['paid']; // Find the paid value matching that customer ID
$a['paid'] = $paid;
}

更新
如果您需要它来匹配 ID 和到期日期,请使用 array_filter() 来获取 $arr1 中与日期和 ID 匹配的数组元素.使用 reset(),我们使用该数组中的第一个元素。

foreach ($arr2 as &$a) {
// Find the sub-array of $arr1 that matches this array's date and ID
$arr1_match = array_filter($arr1, function($v) use ($a) {
return $v['customer_id'] == $a['customer_id'] && $v['Expire'] == $a['Expire'];
});
// Get the first element from the result
$paid = reset($arr1_match)['paid'];
// Append the paid-value to this array (done by reference)
$a['paid'] = $paid;
}

关于php - 将第一个数组的特定键和值合并到第二个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55588353/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com