按(例如:标题或描述)值中的关键字过滤多维数组 (PHP)

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

如何使用 'title' 或 'description' 值中的特定关键字过滤多维数组,如下面的数据数组:

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
                )
        )

)

以前我使用下面的代码,它根据我的需要工作和显示,但同时我收到错误消息 "Notice: Array to string conversion".

$search = "/mark/i";

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

我是不是遗漏了一些代码?或者,还有更好的方法。 提前谢谢你

您收到此通知是因为键 category 数组 。 PHP 尝试将此数组转换为字符串以便应用 preg_grep,这就是您收到此警告的原因。我想你可以这样做:

$search = "mark";

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

已更新 变体 - 未设置数组值和 运行 preg_grep 其余值,即字符串:

$search = "/mark/i";

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