下面有一个多维数组。我正试图根据传递给函数的值来获取数组的某些部分。但由于某种原因,即使path
匹配,它也会返回false,只有在使用/test
时它才会返回一些东西,但如果我键入/hello
,if
会失败,它会返回false
。
这是阵列:
Array
(
[0] => Array
(
[name] => test_route
[path] => /test
[controller] => TestController
[action] => indexAction
)
[1] => Array
(
[name] => hello_route
[path] => /hello
[controller] => HelloController
[action] => helloAction
)
)
这是一种方法:
public function getRoute($path = "", $name = "")
{
foreach($this->routes as $key => $val)
{
if($val['path'] === $path || $val['name'] === $name)
{
return $this->routes[$key];
}
else
{
return false;
}
}
}
只需修改您提供的代码,您可能应该尝试以下操作:
public function getRoute($path = "", $name = "")
{
foreach($this->routes as $key => $val)
{
if($val['path'] === $path || $val['name'] === $name)
{
return $this->routes[$key];
}
}
return false;
}
您的方法在检查第一个元素后就存在了。移除else块,并将返回false放在循环之外。
foreach($this->routes as $key => $val)
{
if($val['path'] === $path || $val['name'] === $name)
{
return $this->routes[$key];
}
}
return false;
我不知道/test
为什么能工作。您正在处理一个多维数组。foreach不进行深度搜索。你将不得不修改你的代码如下:
public function getRoute($path = "", $name = "")
{
foreach($this->routes as $route) {
foreach($route as $key => $val)
{
if($val['path'] === $path || $val['name'] === $name)
{
return $route[$key];
}
}
}
return false;
}