简体   繁体   中英

PHP array search within array

$keywords = array('red', 'blue', 'yellow', 'green', 'orange', 'white');

$strings = array(
'She had a pink dress',
'I have a white chocolate',
'I have a green balloon',
'I have a chocolate shirt',
'He had a new yellow book',
'We have many blue boxes',
'I have a magenta tie');

In reality the strings array is really huge (50k+ entries).

What is the best way of running search and extracting the matching strings only ?

The best way is to use array_filter() .

$filtered_array = array_filter($strings,'filter');

function filter($a)
{
    $keywords = array('red', 'blue', 'yellow', 'green', 'orange', 'white');

    foreach ($keywords as $k)
    {
        if (stripos($a,$k) !== FALSE)
        {
            return TRUE;
        }
    }

    return FALSE;
}

Use array_filter to filter the $strings array.
Split the strings into an array, then trim each word, and use array_intersect to check if the array of words contains any of the $keywords .

$result = array_filter($strings, function($val) use ($keywords) {
    return array_intersect( array_map('trim', explode(' ', $val)) , $keywords);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM