基于搜索值部分匹配的过滤多维数组
我正在寻找给定此数组的函数:
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'
解决方案
使用array_filter
。您可以提供一个回调,该回调决定哪些元素保留在数组中,哪些应该删除。(回调的返回值false
表示应该删除给定的元素。)类似以下内容:
$search_text = 'Bread';
array_filter($array, function($el) use ($search_text) {
return ( strpos($el['text'], $search_text) !== false );
});
有关详细信息:
array_filter
strpos
return values
相关文章