问题
I have two associative array having one value in common, like
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"
}
)
I would like to merge them both by their ID. A simple merge isn't possible because they arn't sorted, have 40.000 + values and don't have the same size.
I planned to use a double foreach, and create a third array were the ID was common, I dropped the idea. Since having to parse 40.000 values in the first array for each of the 40.000 values from the second array take too long.
Is there some solution ? I would like to having it look like this at final :
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"
}
)
回答1:
You cannot avoid to loop. But foreach is pretty fast. Tested on an array of 50.000 and it took 0.04 seconds.
What this wil do is:
- create a TMP array
- get the KEY and ID values from ARRAY1
- put them as 'ID'=>key in the TMP array
- loop ARRAY2, get the ID
- look up the corresponding ID in TMP
- get the key from ARRAY1
- merge ARRAY1 and ARRAY2
You'll end up with ARRAY1 having the data from 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] );
}
}
回答2:
https://eval.in/1011901
<?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));
OUTPUT
array(2) {
[0]=>
array(2) {
["ID"]=>
string(4) "TOTO"
["COUCOU"]=>
int(2)
}
[1]=>
array(2) {
["ID"]=>
string(4) "TATA"
["RA"]=>
string(1) "T"
}
}
来源:https://stackoverflow.com/questions/50587034/merge-two-associative-arrays-by-same-key