【问题标题】:How can I filter out certain items in an array using php?如何使用 php 过滤掉数组中的某些项目?
【发布时间】:2013-09-19 23:16:27
【问题描述】:

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

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

$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

我不太清楚“function($x) use....”在做什么...我对 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" 保留在数组中。我不知道我做错了什么。

感谢任何帮助。

提前致谢。

【问题讨论】:

  • 从您所说的错误中看起来很明显。 preg_match() 期望参数 2 是字符串,你传递给它一个数组。所以我不得不问:即使不是你写的,你明白这段代码是做什么的吗?
  • 我不知道 $x 是什么以及它是如何填充的...这可能是我不明白的原因...是 $rResult 被放入 $x 吗?
  • 那么你真的需要先坐下来阅读ca3.php.net/manual/en/function.array-filter.php - 它解释了参数的作用,并向你展示了它的使用示例。

标签: php regex


【解决方案1】:

问题是多维数组。当您传递给回调时,$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;
        }
    }
);

【讨论】:

    【解决方案2】:

    试试这样的:

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

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

    【讨论】:

    • use 关键字用于匿名函数,表示应将变量视为范围内。这就像调用global $shortWords 而不调用global
    猜你喜欢
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 2012-02-02
    • 2021-05-09
    • 2015-07-04
    • 2016-08-02
    相关资源
    最近更新 更多