PHP使用array_filter查找二维数组中符合字段和字段值的数据集合

Posted muzi-lee

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP使用array_filter查找二维数组中符合字段和字段值的数据集合相关的知识,希望对你有一定的参考价值。

1、方法:

 1     /**
 2      * 获取符合字段和字段值的数组集合
 3      * @param array $data 待过滤数组
 4      * @param string $field 要查找的字段
 5      * @param $value 要查找的字段值
 6      * @return array 返回所有符合要求的数组集合
 7      */
 8     public static function arrayFilterFieldValue(array $data, string $field, $value)
 9     {
10         $data = array_filter($data, function ($row) use ($field, $value) {
11             if (isset($row[$field])) {
12                 return $row[$field] == $value;
13             }
14         });
15         return $data;
16     }

2、示例,查找下面二维数组中name为“张三”的所有数据,原数组如下:

技术图片

 3、调用方式如下:

 1 $arr = [
 2     [
 3         ‘id‘ => 1,
 4         ‘name‘ => ‘张三‘,
 5     ], [
 6         ‘id‘ => 2,
 7         ‘name‘ => ‘李四‘,
 8     ], [
 9         ‘id‘ => 3,
10         ‘name‘ => ‘王五‘,
11     ], [
12         ‘id‘ => 4,
13         ‘name‘ => ‘马六‘,
14     ], [
15         ‘id‘ => 5,
16         ‘name‘ => ‘张三‘,
17     ], [
18         ‘id‘ => 6,
19         ‘name‘ => ‘张三‘,
20     ], [
21         ‘id‘ => 6,
22         ‘name‘ => ‘李四‘,
23     ],
24 ];
25 $data = Helper::arrayFilterFieldValue($arr, ‘name‘, ‘张三‘);

4、打印$data结果如下:

技术图片

 5、相关函数:

array_filter():用回调函数过滤数组中的单元。

以上是关于PHP使用array_filter查找二维数组中符合字段和字段值的数据集合的主要内容,如果未能解决你的问题,请参考以下文章

PHP 数组处理

PHP:如何使用 array_filter() 过滤数组键?

PHP 数组过滤空值 array_filter

array_filter() 期望参数 1 是 PHP 中的数组

php利用array_filter()过滤数组空值

PHP array_filter() 函数详解