我有两个关联数组有一个共同的值,比如
ARRAY 1(
[0]=>
array(2) {
["ID"]=> "AAAA"
["Name"]=> "Apple"
}
[1]=>
array(2) {
["ID"]=> "BBBB"
["Name"]=> "Avocado"
}
[3]=>
array(2) {
["ID"]=> "CCCC"
["Name"]=> "Banana"
}
)
Array2 (
[0]=>
array(4) {
["ID"]=> "AAAA"
["Taste"]=> "Yumi"
["Location"]=> "France"
["Price"]=> "Cheap"
}
[1]=>
array(4) {
["ID"]=> "CCCC"
["Taste"]=> "Yumi"
["Location"]=> "Africa"
["Price"]=> "Cheap"
}
[3]=>
array(4) {
["ID"]=> "BBBB"
["Taste"]=> "Yumi"
["Location"]=> "America"
["Price"]=> "Expansive"
}
[3]=>
array(4) {
["ID"]=> "HZGA"
["Taste"]=> "Berk"
["Location"]=> "Moon"
["Price"]=> "Expansive"
}
)
我想通过他们的ID合并它们。 一个简单的合并是不可能的,因为它们没有排序,有40.000 +值,并且没有相同的大小。
我计划使用双foreach,并创建第三个数组,ID很常见,我放弃了这个想法。由于必须在第一个数组中为第二个数组中的每个40.000值解析40.000个值,所以需要太长时间。
有解决方案吗?我希望最终看起来像这样:
ArrayFinal (
[0]=>
array(4) {
["ID"]=> "AAAA"
["Name"]=> "Apple"
["Taste"]=> "Yumi"
["Location"]=> "France"
["Price"]=> "Cheap"
}
[1]=>
array(4) {
["ID"]=> "CCCC"
["Name"]=> "Banana"
["Taste"]=> "Yumi"
["Location"]=> "Africa"
["Price"]=> "Cheap"
}
[3]=>
array(4) {
["ID"]=> "BBBB"
["Name"]=> "Avocado"
["Taste"]=> "Yumi"
["Location"]=> "America"
["Price"]=> "Expansive"
}
)
答案 0 :(得分:2)
<?php
$a = [['ID'=> 'TOTO'], ['ID' => 'TATA']];
$b = [['ID' => 'TATA', 'RA' => 'T'], ['ID' => 'TOTO', 'COUCOU' => 2]];
$final = [];
foreach($a as $c){
if(!isset($final[$c['ID']])){
$final[$c['ID']] = $c;
}else{
$final[$c['ID']] += $c;
}
}
foreach($b as $c){
if(!isset($final[$c['ID']])){
$final[$c['ID']] = $c;
}else{
$final[$c['ID']] += $c;
}
}
var_dump(array_values($final));
<强>输出强>
array(2) {
[0]=>
array(2) {
["ID"]=>
string(4) "TOTO"
["COUCOU"]=>
int(2)
}
[1]=>
array(2) {
["ID"]=>
string(4) "TATA"
["RA"]=>
string(1) "T"
}
}
答案 1 :(得分:0)
你无法避免循环。但是foreach非常快。测试了50.000的数组,花了0.04秒。
这将做的是:
您最终会获得ARRAY1来自ARRAY2的数据
$ar1=[...]; //original array 1
$ar2=[...]; //original array 2
// get ID=> key pairs
$kv=[];
foreach($ar1 as $k => $v){
$kv[ $v['id'] ] = $k;
}
// loop ARRAY2
foreach($ar2 as $k => $v){
if( array_key_exists( $v['id'] , $kv ) ){
$ar1[ $kv[$v['id']] ] = array_merge( $ar1[$kv[$v['id']]] , $ar2[$k] );
}
}