[英]Match an array value with a string and return the array PHP
我有这样的数组
0 => array:4 [▼
"Name" => "Aroma Therapy - 45 minutes"
"ID" => "1000000015"
"Price" => "50.00"
"Category" => "Aroma"
]
1 => array:4 [▼
"Name" => "Aroma Therapy - 60 Minutes"
"ID" => "0000000003"
"Price" => "100.00"
"Category" => "Aroma"
我想要实现的是,每当用户搜索'therapy'
或'aroma'
,我想匹配此数组的名称并返回它的价格和ID。
我尝试使用strpos()
strstr()
和正则表达式,我可以找到搜索是否匹配,但我无法获得匹配时返回数组的功能。
因此,如果用户搜索'therapy'
,我想在一个名为$result
的变量中返回上面的两个数组。 所以我可以像这样访问它的名称,ID和价格
$result->Name, $result->ID, $result->Price
关于如何实现这种功能的任何想法?
使用array_filter
和stripos()
,您可以获取数组项
stripos
- 查找字符串中第一次出现不区分大小写的子字符串的位置
array_filter
- 使用回调函数过滤数组的元素
// keyword to be searched
$keyword = 'aroma';
// you will get all array items of matched
$result_array = array_filter($array, function($item) use ($keyword) {
return ( stripos($item['Name'], $keyword) !== false );
});
// to convert to object
$object = json_decode( json_encode($result_array) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.