28

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

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

3 回答 3

53

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

$search_text = 'Bread';

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

了解更多信息:

于 2011-08-03T19:56:50.360 回答
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',
  ),
)
于 2020-09-17T00:13:39.737 回答
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])
 }

 }
于 2011-08-03T21:14:42.760 回答