Search code examples
phparraysarray-filterpreg-grep

Filter multidimensional array by keywords in (ex: title or description) values (PHP)


How to filter multidimensional array with specific keyword in 'title' OR 'description' values, like the data array below:

Array
(
    [0] => Array
        (
            [id] => 873
            [title] => Mark
            [description] => John Doe Billy
            [category] => Array
                (
                    [id] => 52
                    [name] => Wall Art
                )
        )

    [1] => Array
        (
            [id] => 266
            [title] => Ninja Turle
            [description] => Mark Doe
            [category] => Array
                (
                    [id] => 52
                    [name] => Wall Art
                )
        )

    [2] => Array
        (
            [id] => 227
            [title] => Red Rose 
            [description] => Billy Jean
            [category] => Array
                (
                    [id] => 52
                    [name] => Wall Art
                )
        )

)

previously i used below code, and it worked and display according to what I needed, but at the same time i got error msg "Notice: Array to string conversion".

$search = "/mark/i";

$products = array_filter($data, function($a) use($search)  {
    return preg_grep($search, $a);
});

Am I missing something with the code? or is there a better way. Thank you in advance


Solution

  • You get this notice because key category is array. PHP tries to convert this array to string so as to apply preg_grep, that's why you receive this warning. I suppose you can do something like:

    $search = "mark";
    
    $products = array_filter($data, function($a) use($search)  {
        return false !== stripos($a['title'], $search) 
            || false !== stripos($a['description'], $search);
    });
    

    Updated variant - unset array value and run preg_grep on the rest of values, which are strings:

    $search = "/mark/i";
    
    $products = array_filter($data, function($a) use($search)  {
        unset($a['category']);
        return preg_grep($search, $a);
    });