我想从$ routes数组中获取匹配路由。如果有多个数组具有相同的“ ur”值。我想全部拿走。
普通数组项看起来像;
[
"controller" => "RegisterController",
"method" => "GET",
"url" => "/register",
"action" => "index"
]
Run Code Online (Sandbox Code Playgroud)
我正在使用我的get_in_array方法获取商品;
$routes = unserialize(apcu_fetch("routes"));
$route = get_in_array($this->url, $routes, "url");
Run Code Online (Sandbox Code Playgroud)
帮手
function get_in_array(string $needle,array $haystack,string $column){
$key = array_search($needle, array_column($haystack, $column));
// even if there are more than one same url, array search returns first one
if (!is_bool($key)){
return $haystack[$key];
}
}
Run Code Online (Sandbox Code Playgroud)
但是array_search()方法只返回第一个匹配项。如果有两个具有相同网址的数组(例如"/register"),则无法同时获取它们。如何获得多个匹配结果?
在array_search手册中有提及:
要返回所有匹配值的键,请改用
array_keys()可选search_value参数。
所以,代替
$key = array_search($needle, array_column($haystack, $column));
Run Code Online (Sandbox Code Playgroud)
使用
$keys = array_keys(array_column($haystack, $column), $needle); // notice order of arguments
Run Code Online (Sandbox Code Playgroud)