如果我可以返回一個數組,如果它與一個特定的字段相匹配。搜索數組並返回數組
爲了使它更清晰,假設我有一個數組,它看起來像這樣---
[1] => Array
(
[id] => 11
[category] => phone cases
[sale_price] => 90,99
[price] => 120
[product_name] => "iphone 6 plus" case transparent
)
[2] => Array
(
[id] => 13
[category] => shoes
[sale_price] => 180,99
[price] => 200
[product_name] => blue platform shoes
)
[3] => Array
(
[id] => 14
[category] => wallet
[sale_price] => 150
[price] => 250
[product_name] => valvet wallet
所以我想這裏是什麼,如果我搜索valvet應該在陣列的搜索[product_name]字段,並返回與其他字段的數組。
例如---
如果我搜索valvet它應該返回 -
[0] => Array
(
[id] => 14
[category] => wallet
[sale_price] => 150
[price] => 250
[product_name] => valvet wallet
)
這是我的PHP代碼,我所試圖做的事 -
$data = 'plus'; // what i want to search
$search = my_array_search($all_data, $data);
function my_array_search($array, $string)
{
$ret = false;
$pattern = preg_replace('/\s+/', ' ', preg_quote($string, '/'));
foreach($array AS $k => $v) {
$res = preg_grep('/' . $pattern . '/', $v);
if(!empty($res)) $ret[$k] = $res;
}
return $ret;
}
但它只返回["product_name"]
不是匹配的數組!
我該如何解決,有人可以幫我解決這個問題!
非常感謝你的偉大的答案:) –