0

So I have a string $key which is something along the lines of system.style.background which I explode at character '.' to $exp. I also have some decoded JSON $system.

I would like to do something like this

echo $system[$exp[0]][$exp[1]][$exp[2]]

which would be

echo $system["system"]["style"]["background"]

However, $key could be any string, with n amount of delimiters. Such as

  • system
  • system.style
  • system.style.background
  • system.style.background.description

How would I write a function that takes a string and returns the json value like above?

Edit: A jank way of doing it would be

if(isset($exp[0])){
    $config[$exp[0]];
}

if(isset($exp[1])){
    $config[$exp[0]][$exp[1]];
}

if(isset($exp[n])){
    $config[$exp[0]][$exp[1]][$exp[n]];
}

Edit: Not duplicate because this is an associative array

3

2 Answers 2

2

Apparently PHP is missing a built in function to access deep arrays of dynamic depth. But it can be done with the infamous eval function. Read the linked disclaimer and use with care.

$system["system"]["style"]["background"]["description"] = "found it";

$input = "system.style.background.description";
$exp = explode(".", $input);

$code = '$system';
foreach ($exp as $level) $code .= "['$level']";

eval("\$result = $code;");
var_dump($result);
Sign up to request clarification or add additional context in comments.

2 Comments

This is exactly what I was looking for, thank you for the solution and thank you for linking the disclaimer.
Not sure where 'system.style.background.description' is actually coming from in the OP's question, but definitely do your validation checks on the $level variable before blindly tossing it in. As far as security impact levels are concerned when dealing with remote applications/endpoints, things like the code above are an absolute critical vulnerability, and if $input is provided by the user, then the code above would result in an extremely insecure server. Not knocking the solution, but definitely do your due diligence to sanitize the input.
0

Not sure of what you are asking but this may solve your problem :)

$config = ...
$exp = ...
$i = 0;

while (isset($exp[$i])){
    $config = $config[$exp[$i]];
    ++$i;
}

$config // There you have your final config

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.