所以我正在尋找將字串轉換為 var 的方法...我需要從陣列 $Map 中獲取資料作為鍵,我使用 $URL 從真實 URL 獲取資料并將其分開... $URL = explode("/",$網址); 所以當我訪問 $Map 的值時,它需要這樣寫:
$Map[$URL[0]][$URL[1]][$URL[2]][$URL[3]][$URL[4]][$URL[5]]
所以我決定創建生成 [$URL[0]] 之類的函式
function GenerateURl($i){for ($x = 0; $x <= $i; $x ){
$URls.='$URL['.$x.']';
}
return($URls);}
為什么?我有可以托管訪問的頁面地圖,這就是 $MAP 包含的內容,每個維度都有樣式和內容設定,但我真的不想手動輸入每個維度 維護它的痛苦......
if($Map[$URL[0]){ #Check if first dimension exist (Index.php/example)
if....... #this take much more steps to verify if there is request for child, and if child exist, ofc there is else method that redirect to closest parent page
$Style="style_for_page.css";
$Contend="style_for_page.css";
}
else{
header("Location: https://example.com");
}
我不知道我做錯了什么...但是當我呼叫我的函式 GenerateURl(5) 輸出是字串...不作業 var...所以它就像
$URL[0]$URL[1]$URL[2]$URL[3]$URL[4]
不喜歡
組態檔用戶設定隱私示例......(example.com/Profile/User/Settings/Privacy/Examle)
更新:為了簡化我的問題......我需要這個:
$MAP = array(........) ;
$URL = array("example");
$var = "[$URl[0]]"; #$URL need to be transferred as text to print part
Print($Map[$var]);
uj5u.com熱心網友回復:
您不能完全按照您想象的方式執行此操作 - PHP 無法生成可執行的陣列訪問代碼集(好吧,您可以,然后使用eval執行它,但您真的不想這樣做除非沒有其他選擇)。
更好的方法是將引數傳遞給輔助函式,該函式將使用提供的每個引數逐步遍歷目標陣列。
另一個任務當然是使用explode. 看起來你想忽略第一部分(協議和域),只看路徑的元素。
這段代碼應該做你需要的,我認為:
function flatCall($data_arr, $data_arr_call){
$current = $data_arr;
foreach($data_arr_call as $key){
$current = $current[$key];
}
return $current;
}
$MAP = array("profile" => array("setting" => array("test" => array("idknow" => "someValue"))));
$urlString = "www.example.com/profile/setting/test/idknow";
$URL = explode("/", $urlString); //split URL string into an array
array_shift($URL); //remove first element
$result = flatCall($MAP, $URL);
echo $result;
現場演示:https ://3v4l.org/A3Z1H
歸功于https://stackoverflow.com/a/36334761/5947043的輔助功能 - 閱讀該答案以了解其作業原理。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/511286.html
標籤:php数组变量多维数组
