在Array中搜索部分值匹配

时间:2011-08-03 19:54:24

标签: php search multidimensional-array

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

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'

4 个答案:

答案 0 :(得分:40)

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

$search_text = 'Bread';

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

了解更多信息:

答案 1 :(得分:9)

check this answer

$filenames=array("120_120_435645.jpg","150_150_312312.jpg","250_250_1232327.jpg");
$matches = preg_grep("/312312/", $filenames);

答案 2 :(得分:2)

从PHP8开始,有一个新函数可以返回布尔值来表示字符串中是否存在子字符串(这是对strpos()的更简单替换)。

str_contains()

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

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

答案 3 :(得分:0)

是多阵列的原因吗? 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])
 }

 }