2 回答
TA贡献1966条经验 获得超4个赞
您的代码不起作用,因为函数应该始终具有返回值 - 在递归中它是必需的:
function test($menu) {
$url = "test.com/accounts/overview/";
foreach($menu as $data) {
if( is_array($data) &&
isset($data["t_link"]) &&
$data["t_link"] === $url ) {
return $data["t_icon"];
}
else if (is_array($data)) {
$result = test($data); //Get result back from function
//If it's NOT NULL call the function again (test($data))
//
//(down below returns null when looped through
//everything recursively)
//
if ($result !== null) {
return $result;
}
}
}
return null;
}
这是实现您想要的 OOP 风格的另一种方法:
该解决方案背后的想法是创建一个两级数组(不多也不少)并从该新数组中获取数据。
class Searcher {
private $new_arr = array();
private $icon = '';
//array_walk_recursive goes through your array recursively
//and calls the getdata-method in the class. This method creates
//a new array with strings (not arrays) from supplied $array ($menu in your case)
public function __construct($array, $search_url) {
array_walk_recursive($array, array($this, 'getdata'));
$key = array_search($search_url, $this->new_arr['t_link']);
$this->icon = $this->new_arr['t_icon'][$key];
}
public function geticon() {
return $this->icon;
}
public function getdata($item, $key) {
if (!is_array($item)) {
$this->new_arr[$key][] = $item;
}
}
}
//Implementation (usage) of above class
$search = new Searcher($menu, 'test.com/accounts/overview/');
$icon = $search->geticon();
echo 'ICON=' . $icon; //Would echo out 'fa fa-book'
进一步说明:
基于你的$menu数组,该类将创建一个像这样的数组($this->new_arr):
Array
(
[t_link] => Array
(
[0] => test.com
[1] => test.com/accounts
[2] => test.com/accounts/overview/
)
[t_icon] => Array
(
[0] => fa fa-dashboard
[1] => fa fa-books
[2] => fa fa-book
)
)
新数组中的所有键都相互关联。这是$this->new_arr[$key][] = $item; 在getdata()方法中设置的。这是基于这样一个事实,即数组中的t_link-keys 和-keys的数量必须相等。t_icon
因为这:
$this->new_arr[0]['t_link'] is related to $this->new_arr[0]['t_icon'];
$this->new_arr[1]['t_link'] is related to $this->new_arr[1]['t_icon'];
$this->new_arr[2]['t_link'] is related to $this->new_arr[2]['t_icon'];
etc.. (not more in your example)
有此代码时:
$key = array_search($search_url, $this->new_arr['t_link']);
如果您已提供给test.com/accounts/overview/,它将提供密钥2$search_url
所以:
$this->icon = $this->new_arr['t_icon'][$key];
设置为fa fa-book
TA贡献2036条经验 获得超8个赞
因为你在函数内部调用函数,你必须返回函数的值,这里是修复:(在 test($data); 之前添加“return”)
function test($menu) {
$url = "test.com/accounts/overview/";
foreach($menu as $data) {
if( is_array($data) and array_key_exists("t_link", $data) and $data["t_link"] == $url ) {
return $data["t_icon"];
} else if(isset($data["Overview"])) {
return test($data);
}
}
}
此外,所有这三种情况,它们都是数组,因此return test($data);将停止 foreach 然后$menu["Accounts"]["Overview"]永远不会被检查。
- 2 回答
- 0 关注
- 144 浏览
添加回答
举报