Compare 2 arrays on single element in php

101 Views Asked by At

I have two arrays that look like this with many more results:

Array
(
   [0] => Array
    (
        [comName] => John
        [locID] => L152145
        [locName] => Johns House

               )
)

What i'd like to do is compare the results but only on the locName element...here is the code i'm working with thus far.

$searchcode = "a url to json results"; 
$simple = file_get_contents($searchcode);
$arr = json_decode($simple , true);

do this for each json file then

 $result = array_intersect($arr, $anotherarr);

Ideally this would return the matching locNames from both arrays

Thanks for the help!

2

There are 2 best solutions below

1
On BEST ANSWER

What you are a looking for is function array_uintersect:

$result = array_uintersect($arr, $anotherarr, function($a, $b) { return strcmp($a['locName'], $b['locName']); });
1
On

If each locName will appear only once, then I suggest you transform your array in an associative one in the form

Array
(
   [Johns House] => Array
    (
        [comName] => John
        [locID] => L152145
        [locName] => Johns House

     )
)

This way, you'll have access to every location name using array_keys, and will be able to pick the locations that are present in both arrays with a simple array_intersect on both array_keys.

The simplest way to do this is to iterate over the original array filling a new one (not really efficient if you're planning to manage 10000+ elements, but negligible in other case)

$assocA=array();
$assocB=array();

foreach($arr as $element) {
    $assocA[$element['locName']]=$element;
}

foreach($anotherarr as $anotherelement) {
    $assocB[$anotherelement['locName']]=$anotherelement;
}

$common_locations = array_intersect(array_keys($assocA), array_keys($assocB)); // will return all locnames present in both arrays.