"RegisterControl-6ren">
gpt4 book ai didi

php - 如何使用 array_search() 获取多个键?

转载 作者:行者123 更新时间:2023-12-05 08:23:05 24 4
gpt4 key购买 nike

我想从 $routes 数组中获取匹配的路由。如果有多个数组具有相同的“ur”值。我想得到所有这些。

普通的数组项看起来像;

[
"controller" => "RegisterController",
"method" => "GET",
"url" => "/register",
"action" => "index"
]

我正在使用我的 get_in_array 方法获取项目;

$routes = unserialize(apcu_fetch("routes"));
$route = get_in_array($this->url, $routes, "url");

助手

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];
}
}

但是 array_search() 方法只返回第一个匹配项。如果有两个具有相同 url 的数组(如 "/register"),我无法同时获取它们。如何获得多个匹配结果?

最佳答案

array_search手册中提到:

To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.

所以,而不是

$key = array_search($needle, array_column($haystack, $column));

使用

$keys = array_keys(array_column($haystack, $column), $needle);  // notice order of arguments

关于php - 如何使用 array_search() 获取多个键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50822067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com