php 基于搜索值部分匹配的多维数组过滤

blmhpbnm  于 5个月前  发布在  PHP
关注(0)|答案(3)|浏览(41)

我正在寻找一个函数,给定这个数组:

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'

0ejtzxu1

0ejtzxu11#

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

$search_text = 'Bread';

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

字符串
更多信息:

ac1kyiln

ac1kyiln2#

在PHP 8中,有一个新的函数可以返回一个布尔值来表示一个子字符串是否出现在一个字符串中(这是作为strpos()的一个更简单的替代品)。
str_contains()
如果需要不区分大小写,那么str_contains()的区分大小写匹配就不够了。使用stripos()

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

字符串
如果需要单词边界,则使用带有\b元字符的正则表达式。
这需要在迭代函数/构造中调用。
从PHP7.4开始,可以使用箭头函数来减少整体语法,并将全局变量引入自定义函数的作用域。
代码:(Demo

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

imzjd6km

imzjd6km3#

有多个数组的原因。是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 ='bread';

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])
 }

 }

相关问题