So Im looking for way to convert string into var... I need do get data from array $Map As key I use $URL that get data from real URL and seperate it... $URL = explode("/",$URL); So when I access values of $Map it need to be written like this:
$Map[$URL[0]][$URL[1]][$URL[2]][$URL[3]][$URL[4]][$URL[5]]
So I decide to create function that generate amount of [$URL[0]]'s like
function GenerateURl($i){for ($x = 0; $x <= $i; $x ){
$URls.='$URL['.$x.']';
}
return($URls);}
Why? I have map of pages that can host visit , thats what $MAP contains, each dimension has style and content setting, but I really dont want to type every single dimension manually its pain to maintace it...
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");
}
I dont know what I do wrong... But when I call my function GenerateURl(5) output is string... not working var... so its like
$URL[0]$URL[1]$URL[2]$URL[3]$URL[4]
and not like
Profile User Settings Privacy Examle...... (example.com/Profile/User/Settings/Privacy/Examle)
Update: To simplify my question... I need this:
$MAP = array(........) ;
$URL = array("example");
$var = "[$URl[0]]"; #$URL need to be transferred as text to print part
Print($Map[$var]);
CodePudding user response:
You can't quite do this in exactly the way you're imagining - PHP can't generate an executable set of array access code (well, you could, and then execute it using eval, but you really don't want to do that unless there's no other option).
A better way is to pass the arguments to a helper function which will then iterate through the target array gradually using each of the arguments provided.
The other task of course is to split the URL string into parts using explode
. It looks like you want to ignore the first parts (protocol and domain) and just look at the elements of path.
This code should do what you need, I think:
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;
Live demo: https://3v4l.org/A3Z1H
Credit to https://stackoverflow.com/a/36334761/5947043 for the helper function - read that answer for an explanation of how it works.