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 關注
- 171 瀏覽
添加回答
舉報