基于搜索值部分匹配的多维数组筛选

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

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'

答案 1

使用array_filter。您可以提供一个回调,用于决定哪些元素保留在数组中以及应删除哪些元素。(回调返回值指示应删除给定元素。像这样:false

$search_text = 'Bread';

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

欲了解更多信息:


答案 2

从 PHP8 开始,有一个新函数返回一个布尔值来表示字符串中是否出现子字符串(这是作为更简单的替代项提供的)。strpos()

str_contains()

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

从 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',
  ),
)

推荐