php 在数组中搜索部分值匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6932438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Search for partial value match in an Array
提问by Chamilyan
I'm looking for a function where given this 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..
I want to search for the needle
我要找针
"Bread"
“面包”
and get the following result
并得到以下结果
[1] =>
array(
['text'] =>'I like Apples and Bread'
['id'] =>'283923'
)
[2] =>
array(
['text'] =>'I like Apples, Bread, and Cheese'
['id'] =>'3384823'
回答by Jon Gauthier
Use array_filter
. You can provide a callback which decides which elements remain in the array and which should be removed. (A return value of false
from the callback indicates that the given element should be removed.) Something like this:
使用array_filter
. 您可以提供一个回调来决定哪些元素保留在数组中,哪些应该被删除。(false
回调的返回值表示应该删除给定的元素。)像这样:
$search_text = 'Bread';
array_filter($array, function($el) use ($search_text) {
return ( strpos($el['text'], $search_text) !== false );
});
For more information:
想要查询更多的信息:
回答by arod
also check this answer
$filenames=array("120_120_435645.jpg","150_150_312312.jpg","250_250_1232327.jpg");
$matches = preg_grep("/312312/", $filenames);
回答by amigura
is there a reason for multi array. is id unique and can it be used as index.
多阵列有原因吗?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';
$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])
}
}