一尘不染

在数组中搜索部分值匹配

php

我正在寻找给定此数组的函数,

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'

阅读 275

收藏
2020-05-29

共1个答案

一尘不染

使用array_filter。您可以提供一个回调,该回调确定哪些元素保留在数组中以及哪些元素应删除。(false从回调返回的值指示应删除给定的元素。)类似这样的东西:

$search_text = 'Bread';

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

欲获得更多信息:

2020-05-29