1

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?

1

1 Answer 1

3

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']]);
});
Sign up to request clarification or add additional context in comments.

Comments

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.