如何使用 php 过滤掉数组中的某些项目


How can I filter out certain items in an array using php?

我想根据一些搜索条件过滤掉一个php数组,但它不太有效。

我一直在尝试我在谷歌上找到的这段代码,但它给出了错误?

$shortWords = '/'.$_GET['sSearch'].'/i';
$rResult = array_filter($rResult, 
     function($x) use ($shortWords) {
       return preg_match($shortWords,$x);
      });

这是错误:

 preg_match() expects parameter 2 to be string, array given

我不太清楚"功能($x)使用什么......"正在做...我对PHP的局限性。

以下是数组在"array_filter()"之前的样子:

 array(
    [0] =>
        array(
            ['unit_nbr'] =>'BBC 2'
            ['p_unit_group_id'] =>NULL
            ['name'] =>1
            ['unit_id'] =>22640
            ['properties_id'] =>1450
            )
    [1] =>
        array(
            ['unit_nbr'] =>'BBC 3'
            ['p_unit_group_id'] =>NULL
            ['name'] =>1
            ['unit_id'] =>22641
            ['properties_id'] =>1450
) 

我希望在将该搜索字符串传递给函数时unit_nbr"BBC 2"保留在数组中。 我不知道我做错了什么。

任何帮助,不胜感激。

提前谢谢。

问题是多维数组。当你传递给回调时,数组$x

    array(
        ['unit_nbr'] =>'BBC 2'
        ['p_unit_group_id'] =>NULL
        ['name'] =>1
        ['unit_id'] =>22640
        ['properties_id'] =>1450
        )

但是您仍然需要检查该数组中的项目。

$shortWords = '/'.$_GET['sSearch'].'/i';
$rResult = array_filter($rResult, 
    function($x) use ($shortWords) {
        foreach ($x as $_x) {
            if (preg_match($shortWords,$_x)) {
                return true;
            }
            return false;
        }
    }
);

尝试这样的事情:

foreach ($rResult as $okey => $oval) {
    foreach ($oval as $ikey => $ival) {
        if ($ival != $_GET['sSearch']) {
             unset($rResult[$okey]);
        }
    }
}

如果这不是您想要的,那么我需要有关您要实现的目标的更多信息。