2 回答

TA貢獻(xiàn)1966條經(jīng)驗(yàn) 獲得超4個(gè)贊
您的代碼不起作用,因?yàn)楹瘮?shù)應(yīng)該始終具有返回值 - 在遞歸中它是必需的:
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;
}
這是實(shí)現(xiàn)您想要的 OOP 風(fēng)格的另一種方法:
該解決方案背后的想法是創(chuàng)建一個(gè)兩級(jí)數(shù)組(不多也不少)并從該新數(shù)組中獲取數(shù)據(jù)。
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'
進(jìn)一步說明:
基于你的$menu數(shù)組,該類將創(chuàng)建一個(gè)像這樣的數(shù)組($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
)
)
新數(shù)組中的所有鍵都相互關(guān)聯(lián)。這是$this->new_arr[$key][] = $item; 在getdata()方法中設(shè)置的。這是基于這樣一個(gè)事實(shí),即數(shù)組中的t_link-keys 和-keys的數(shù)量必須相等。t_icon
因?yàn)檫@:
$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)
有此代碼時(shí):
$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];
設(shè)置為fa fa-book

TA貢獻(xiàn)2036條經(jīng)驗(yàn) 獲得超8個(gè)贊
因?yàn)槟阍诤瘮?shù)內(nèi)部調(diào)用函數(shù),你必須返回函數(shù)的值,這里是修復(fù):(在 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);
}
}
}
此外,所有這三種情況,它們都是數(shù)組,因此return test($data);將停止 foreach 然后$menu["Accounts"]["Overview"]永遠(yuǎn)不會(huì)被檢查。
- 2 回答
- 0 關(guān)注
- 188 瀏覽
添加回答
舉報(bào)