$json = '[
{
"class1":
{
"function1":"return \"$a<b>$b</b>!\";"
}
},
{
"class2":
{
"function2":"return $b;",
"function3":"return $c;"
}
}
]';
$decoded_classes = json_decode($json,true);
foreach($decoded_classes as $class)
{
$class_name = key($class);
if (is_array($class[$class_name]))
{
foreach($class[$class_name] as $function)
{
$function_name = key($class[$class_name]);
$stack[$class_name][$function_name] = create_function($arr,$function);
}
}
else
{
foreach($class as $function)
{
$c_name = key($class);
$stack[$c_name] = create_function($arr,$function);
}
}
}
return $stack;
I need that this code will execute the same result but with only one foreach. How can i do that?
Translating the JSON to… let’s say “PHPON”, you get:
As you can see, your structure isn’t exactly the most efficient. You basically have one too many levels.
Restructure the JSON like this:
In this way, the “PHPON” is:
Now you don’t even need to loop at all. Accessing
$decoded_classes['class1']['function1']will give you that code. The only thing you have to do is convert those strings into callable functions, like so:I can’t help but notice you didn’t define
$arranywhere in your code. You’ll have to specify$arrcorrectly for this to work.