根据搜索值的部分匹配过滤多维数组

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

我正在寻找一个给定此数组的函数:

array(
 [0] =>
  array(
   ['text'] =>'I like Apples'
   ['id'] =>'102923'
 )
 [1] =>
  array(
   ['text'] =>'I like Apples and Bread'
   ['id'] =>'283923'
 )
 [2] =>
  array(
  ['text'] =>'I like Apples, Bread, and Cheese'
  ['id'] =>'3384823'
 )
 [3] =>
  array(
  ['text'] =>'I like Green Eggs and Ham'
  ['id'] =>'4473873'
 ) 
etc.. 

我想找针

“面包”

并得到以下结果

[1] =>
  array(
   ['text'] =>'I like Apples and Bread'
   ['id'] =>'283923'
 )
 [2] =>
  array(
  ['text'] =>'I like Apples, Bread, and Cheese'
  ['id'] =>'3384823'
php multidimensional-array filtering partial-matches
3个回答
59
投票

使用

array_filter
。您可以提供一个回调来决定哪些元素保留在数组中以及哪些元素应该被删除。 (回调的返回值
false
表示应该删除给定的元素。)像这样:

$search_text = 'Bread';

array_filter($array, function($el) use ($search_text) {
        return ( strpos($el['text'], $search_text) !== false );
    });

欲了解更多信息:


3
投票

从 PHP8 开始,有一个新函数可以返回一个布尔值来表示字符串中是否出现子字符串(这是作为

strpos()
的更简单替代品提供的)。

str_contains()

如果需要不区分大小写,那么

str_contains()
的区分大小写匹配就不够了。使用
stripos()

stripos($subarray['text'], $search) !== false

如果需要单词边界,请使用带有

\b
元字符的正则表达式。

这需要在迭代函数/构造中调用。

从 PHP7.4 开始,可以使用箭头函数来减少整体语法并将全局变量引入自定义函数的范围。

代码:(演示

$array = [
    ['text' => 'I like Apples', 'id' => '102923'],
    ['text' => 'I like Apples and Bread', 'id' =>'283923'],
    ['text' => 'I like Apples, Bread, and Cheese', 'id' => '3384823'],
    ['text' => 'I like Green Eggs and Ham', 'id' =>'4473873']
];

$search = 'Bread';
var_export(
    array_filter($array, fn($subarray) => str_contains($subarray['text'], $search))
);

输出:

array (
  1 => 
  array (
    'text' => 'I like Apples and Bread',
    'id' => '283923',
  ),
  2 => 
  array (
    'text' => 'I like Apples, Bread, and Cheese',
    'id' => '3384823',
  ),
)

1
投票

多阵列有什么原因吗? id 是否唯一,是否可以用作索引。

$data=array(

  array(
   'text' =>'I like Apples',
   'id' =>'102923'
 )
,
  array(
   'text' =>'I like Apples and Bread',
   'id' =>'283923'
 )
,
  array(
  'text' =>'I like Apples, Bread, and Cheese',
  'id' =>'3384823'
 )
,
  array(
  'text' =>'I like Green Eggs and Ham',
  'id' =>'4473873'
 )

 );

$findme='面包';

 foreach ($data as $k=>$v){

 if(stripos($v['text'], $findme) !== false){
 echo "id={$v[id]} text={$v[text]}<br />"; // do something $newdata=array($v[id]=>$v[text])
 }

 }
© www.soinside.com 2019 - 2024. All rights reserved.