phparraysmultidimensional-arrayfilter

Get all first level keys of rows in a 2d array where a column value is partially matched by a search term


I have an array like this one.

$array = Array(
        [0] => Array
            (
                [name] => Eve Greenhaw
                [id] => 456564765
            )

        [1] => Array
            (
                [name] => Tyrone Hallberg
                [id] => 5467652534
            )

        [2] => Array
            (
                [name] => Julio Torbert
                [id] => 254564564
            )

        [3] => Array
            (
                [name] => John Torbert
                [id] => 5462253455
            )

        [4] => Array
            (
                [name] => John Kimmell
                [id] => 4525462
            )

    )

I want to search through the array and return the name and id. For example if the user searches for 'John', I wants the function to return keys 3, and 4. If the user searches for just 'J', the function should return keys 2,3 and 4.


Solution

  • One possibility is array_filter:

    array_filter(array $input, callback $callback)

    Iterates over each value in the input array passing them to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.

    Each member of $array is itself an array, so you could do something like this (assuming you were searching both the name and the id):

    $query = 'whatever';
    
    function single_search($member) {
        global $query;
    
        $in_name = strpos($member['name'], $query);
        $in_id = strpos($member['id'], $query);
    
        return is_numeric($in_name) || is_numeric($in_id);
    }
    
    $filtered = array_filter($array, 'single_search');
    

    The $filtered array contains all the name/id pairs that contained your query. But if you're only interested in the keys, you can use one more function: array_keys. It can return an array of the keys in $filtered, which would be all the keys that matched the query etc etc etc:

    $matched_keys = array_keys($filtered);
    

    Good luck.