Question

Based on my last question , how can I compare the following 2 arrays with array_intersect() ? I would like to compare 1st array's value with 2nd array's inner array's name value.

// $arrayA
[0] => 'apple',
[1] => 'pineapple',
[2] => 'orange',
...
[299,999] => 'banana'

and

// $arrayB
[0] => array('name' => 'bamboo', 'price' => 123),
[1] => array('name' => 'banana', 'price' => 123),
[2] => array('name' => 'boy', 'price' => 123),
[3] => array('name' => 'ball', 'price' => 123),
[4] => array('name' => 'balloon', 'price' => 123),
[5] => array('name' => 'bazooka', 'price' => 123),

My expected result will be in an array, containing the following result:

[1] => array('name' => 'banana', 'price' => 123),

My current workaround is to clone the 2nd array with the inner array's name value only. i.e.

$arrayB_clone = array();
foreach($arrayB as $inner_array) {
  $arrayB_clone[] = $inner_array['name'];
}
$result_index = array_intersect($arrayB_clone, $arrayA);
$result = array();
foreach($result_index as $idx => $v) {
  $result[] = $arrayB[$idx]; // value $v is not important now 
}
var_dump($result);

But as my arrays are with >300,000 records, it will consume a large amount of memory & resources when cloning. Is there any better solution?

Was it helpful?

Solution

You should flip $arrayA so that the lookups are faster. Then simply iterate over B and add the results that match:

$mapA = array_flip($arrayA);

$results = array();

foreach ($arrayB as $item) {
    if (isset($mapA[$item['name']])) {
        $results[] = $item;
    }
}

Or:

$results = array_filter($arrayB, function($item) use ($mapA) {
    return isset($mapA[$item['name']]);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top