我正在寻找一个给定这个数组的函数:
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..
我想找针
并得到以下结果"Bread"
[1] =>
array(
['text'] =>'I like Apples and Bread'
['id'] =>'283923'
)
[2] =>
array(
['text'] =>'I like Apples, Bread, and Cheese'
['id'] =>'3384823'
使用array_filter
。您可以提供一个回调函数来决定哪些元素保留在数组中,哪些元素应该被删除。(回调的返回值false
表示给定的元素应该被删除。)像这样:
$search_text = 'Bread';
array_filter($array, function($el) use ($search_text) {
return ( strpos($el['text'], $search_text) !== false );
});
查看更多信息:
-
array_filter
-
strpos
返回值
从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',
),
)
有多数组的原因吗?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'
)
);
蹄美元=‘面包’;
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])
}
}