Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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']]);
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.