Php 组合两个阵列';在一个大的数据集上创建密钥
我有这个阵列:Php 组合两个阵列';在一个大的数据集上创建密钥,php,arrays,Php,Arrays,我有这个阵列: Array ( [0] => Array ( [id] => 1 [franchise_id] => A123 [brand_id] => 26 [hold_amount] => null ) [1] => Array ( [id] => 2
Array
(
[0] => Array
(
[id] => 1
[franchise_id] => A123
[brand_id] => 26
[hold_amount] => null
)
[1] => Array
(
[id] => 2
[franchise_id] => A123
[brand_id] => 54
[hold_amount] => null
)
)
我有另一个数组:-
Array
(
[0] => stdClass Object
(
[amount_to_settle] => 15.04
[franchise_id] => A123
[brand_id] => 26
)
[1] => stdClass Object
(
[amount_to_settle] => 45.53
[franchise_id] => A123
[brand_id] => 54
)
)
我需要将这两者结合起来,这样我才能得到这样的最终数组:
id
franchise_id
brand_id
hold_amount
amount_to_settle
由于数据集庞大,如何以优化的方式进行此操作您可以使用array_map()
这是参考资料
您可以使用数组合并功能,为避免std类obj错误,请遵循以下格式
您可以在
foreach()
循环中执行此操作
循环
$newArray; //Store in here.
foreach($arrayOne as $k=>$v) {
$key = array_search($v["brand_id"], array_column($arrayTwo, 'brand_id'));
$newArray [] = [
"id" => $v["id"],
"franchise_id" => $v["franchise_id"],
"brand_id" => $v["brand_id"],
"hold_amount" => $v["hold_amount"],
"amount_to_settle" => $arrayTwo[$key]['amount_to_settle'],
] ;
}
var_dump($newArray);;
输出
array(2) {
[0] => array(5) {
["id"] => int(1)
["franchise_id"] => string(4) "A123"
["brand_id"] => int(26)
["hold_amount"] => NULL
["amount_to_settle"] => float(15.04)
}[1] => array(5) {
["id"] => int(2)
["franchise_id"] => string(4) "A123"
["brand_id"] => int(54)
["hold_amount"] => NULL
["amount_to_settle"] => float(45.53)
}
}
编辑:
我没意识到你的钥匙会不同步。它现在使用
array\u search()
和array\u column()
将$arrayOne
中的品牌id
的值与$arrayTwo
匹配。它可能值得添加一个条件,以确保在未找到匹配项时不会中断,但这将在计数不同步的情况下起作用 您想要的输出是什么?@MehulKuriya将这两个数据集结合起来。我在最后一个数组中添加了我需要的键,如果两个数组的计数不相同,这将中断。它们之间有什么关系?您没有提到计数不匹配。数据集都将具有品牌标识和特许经营标识。但是,它可能没有相同的计数请参见更新。它使用array\u search()
和array\u column()
将键brand\u id
与第二个数组匹配。它可能值得添加一个条件,以确保在未找到匹配项时不会中断,但这将在计数不同步的情况下起作用。
$newArray; //Store in here.
foreach($arrayOne as $k=>$v) {
$key = array_search($v["brand_id"], array_column($arrayTwo, 'brand_id'));
$newArray [] = [
"id" => $v["id"],
"franchise_id" => $v["franchise_id"],
"brand_id" => $v["brand_id"],
"hold_amount" => $v["hold_amount"],
"amount_to_settle" => $arrayTwo[$key]['amount_to_settle'],
] ;
}
var_dump($newArray);;
array(2) {
[0] => array(5) {
["id"] => int(1)
["franchise_id"] => string(4) "A123"
["brand_id"] => int(26)
["hold_amount"] => NULL
["amount_to_settle"] => float(15.04)
}[1] => array(5) {
["id"] => int(2)
["franchise_id"] => string(4) "A123"
["brand_id"] => int(54)
["hold_amount"] => NULL
["amount_to_settle"] => float(45.53)
}
}