过滤多维数组并保留任意列中包含指定子字符串的条目

问题描述 投票:0回答:1

我想在多维数组的所有列中搜索子字符串并保留所有符合条件的数据集。

[
    [
        'ConsumerDetail' => [
            'quote_id' => 'QU-12-14-T2887',
            'client_name' => 'asdf asdf',
            'agent_name' => 'flip flob 2313123',
            'zipcode' => 66002,
            'dob' => '01/02/1996',
        ],
    ],
    [
        'ConsumerDetail' => [
            'quote_id' => 'QU-12-14-R4118',
            'client_name' => 'james anderson',
            'agent_name' => 'JOSEPH NEPTUNE',
            'zipcode' => 64656,
            'dob' => '07/16/1958',
        ],
    ],
    [
        'ConsumerDetail' => [
            'quote_id' => 'QU-12-14-W2042',
            'client_name' => 'flip leathers',
            'agent_name' => 'test agen',
            'zipcode' => 65018,
            'dob' => '12/17/1979',
        ],
    ],
]

如果我搜索

flip
,我应该得到一个具有相同结构的数组,其中包含数组的
0
2
索引元素。
0
索引,因为它在
agent_name
列中找到,而
2
因为它在
client_name
列中找到。

所需输出:

array (
  0 => 
  array (
    'ConsumerDetail' => 
    array (
      'quote_id' => 'QU-12-14-T2887',
      'client_name' => 'asdf asdf',
      'agent_name' => 'flip flob 2313123',
      'zipcode' => 66002,
      'dob' => '01/02/1996',
    ),
  ),
  2 => 
  array (
    'ConsumerDetail' => 
    array (
      'quote_id' => 'QU-12-14-W2042',
      'client_name' => 'flip leathers',
      'agent_name' => 'test agen',
      'zipcode' => 65018,
      'dob' => '12/17/1979',
    ),
  ),
)
php arrays multidimensional-array substring filtering
1个回答
0
投票

如果您使用不存在/对比较不重要的分隔符将子数组展平为字符串,那么您可以进行简单的

strpos()
stripos()
检查。

代码:(演示

$needle = 'flip';
var_export(
    array_filter(
        $array,
        fn($row) => stripos(implode('_', $row['ConsumerDetail']), $needle) !== false
    )
);
© www.soinside.com 2019 - 2024. All rights reserved.