Php 在数组中搜索部分值匹配
我在寻找一个函数,给定这个数组Php 在数组中搜索部分值匹配,php,search,multidimensional-array,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
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'
使用。您可以提供一个回调来决定哪些元素保留在数组中,哪些元素应该被删除。(回调的返回值false
表示应删除给定元素。)类似于以下内容:
$search_text = 'Bread';
array_filter($array, function($el) use ($search_text) {
return ( strpos($el['text'], $search_text) !== false );
});
有关更多信息:
$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'
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])
}
}
foreach($k=>v){
if(stripos($v['text'],$findme)!==false){
echo“id={$v[id]}text={$v[text]}
“;//做点什么$newdata=array($v[id]=>$v[text]))
}
}
在PHP8中,有一个新函数返回一个布尔值,以表示子字符串是否出现在字符串中(这是作为strpos()
的更简单替代品提供的)
这需要在迭代函数/构造中调用
从PHP7.4开始,可以使用箭头函数来减少总体语法,并将全局变量邀请到自定义函数的作用域中
代码:()
输出:
array (
1 =>
array (
'text' => 'I like Apples and Bread',
'id' => '283923',
),
2 =>
array (
'text' => 'I like Apples, Bread, and Cheese',
'id' => '3384823',
),
)
更好地使用strpos(…)!=错误。这节省了一个函数调用,而且速度更快。谢谢Hans,出于好奇,“use”操作符是什么?它是否像each循环中的“as”操作符?我找不到有关它的任何信息。
use
关键字使您提供给它的变量在函数范围内可用。默认情况下,在该函数中,$search\u text
是未定义的,因此我们编写use
,让PHP将变量“携带”到本地范围。为什么我会一直收到此错误<代码>解析错误:语法错误,意外的T_函数我甚至尝试直接从@gavsiu复制示例
array (
1 =>
array (
'text' => 'I like Apples and Bread',
'id' => '283923',
),
2 =>
array (
'text' => 'I like Apples, Bread, and Cheese',
'id' => '3384823',
),
)