0

I have two arrays and I need to get the content when the array same Key I'm using array_intersect_key to get the same key and it returns this result:

Array1 :
(
[NewYork] = "5,NewYork";
[london] = "20,london";
[Pari] = "40,Pari";
)

Array2 :
(
[China] = "14,China";
[london] = "40,london";
[Tokyo] = "2,Tokyo";
)

Result

array_intersect_key(Array1,Array2); it return : [london] = "20,london";

But I need to show [london] = "20,london"; and [london] = "40,london";

or something like this [london] = "20,london|40,london";

Without a loop I have a large file

Thank you!

5
  • 1
    You can do this: $res=array_intersect_key($arr1,$arr2); foreach($result as $k=>$v) { $final[$k] = $arr1[$k] ."|".$arr2[$k]; }. $final will be your result. Commented Mar 15, 2018 at 13:07
  • yes but i have more than 90000 line it take many time but with array_intersect_key it faster but is return only one result Commented Mar 15, 2018 at 13:08
  • Then it will take time. Commented Mar 15, 2018 at 13:09
  • 1
    Use $result instead of $res like $result = array_intersect_key($arr1, $arr2); foreach($result as $k=>$v) { $final[$k] = $arr1[$k] ."|".$arr2[$k]; } Commented Mar 15, 2018 at 13:20
  • @FaisalRehman , yes it work thank you very much Commented Mar 15, 2018 at 13:48

1 Answer 1

2

Hi I have tried this code to get the closest result without loop. This might help you.

Code

$array1['NewYork'] = "5,NewYork";
$array1['london'] = "20,london";
$array1['Tokyo'] = "40,Pari";


$array2['China'] = "14,China";
$array2['london'] = "40,london";
$array2['Tokyo'] = "2,Tokyo";


$res1 = array_intersect_key($array1,$array2);
$res2 = array_intersect_key($array2,$array1);

echo "<pre>";
print_r(array_merge_recursive($res1,$res2));
die;

Result

Array
(
    [london] => Array
        (
            [0] => 20,london
            [1] => 40,london
        )

    [Tokyo] => Array
        (
            [0] => 40,Pari
            [1] => 2,Tokyo
        )

)

Let me know if it works. Good Luck.

Update

How about this? It will return the same result.

function myfunction($a,$b)
{
if ($a!=$b)
  {
  return 0;
  }
  return ($a>$b)?1:-1;
}
$array1['NewYork'] = "5,NewYork";
$array1['london'] = "20,london";
$array1['Tokyo'] = "40,Pari";


$array2['China'] = "14,China";
$array2['london'] = "40,london";
$array2['Tokyo'] = "2,Tokyo";

$res1 = array_merge_recursive($array1,$array2);
$res2 = array_uintersect_assoc($res1,$array1,"myfunction");

echo "<pre>";
print_r($res2);
die;
Sign up to request clarification or add additional context in comments.

1 Comment

yes it work thank you , but We do the process twice that mean it take X2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.