There's URL parameter :-
/name/Aario/gender/male/addr[nation][key][sx]/China/addr[city]/Shanghai
As you can notice that there are two array-like string. I want to convert them into array ['addr' => ['nation' => ['key' => ['sx' => China]]], ['city' => 'Shanghai']]
I tried:-
$results = [];
$str = '/name/Aario/gender/male/addr[nation][key][sx]/China/addr[city]/Shanghai/';
$params = explode('/', $str);
if($params[0] == '') unset($params[0]);
while(key($params) !== null && current($params)) {
$key = current($params);
$value = next($params);
if(strpos($key, '[')) {
$sub_keys = explode('[', $key);
foreach($sub_keys as &$sub_key) {
$sub_key = trim($sub_key, ']');
}
$count = count($sub_keys);
$ref = &$results;
foreach($sub_keys as $k => $v) {
if($k == $count - 1) {
$ref[$v] = $value;
$ref = &$ref[$v];
} else {
$ref[$v] = $ref[$v] ?? [];
$ref = &$ref[$v];
}
}
} else {
$results[$key] = $value;
}
next($params);
}
var_dump($results);
It works. It gets:
array(3) {
["name"]=> string(5) "Aario"
["gender"]=> string(4) "male"
["addr"]=> array(2) {
["nation"]=> array(1) {
["key"]=> array(1) {
["sx"]=> string(5) "China"
}
}
["city"]=> &string(8) "Shanghai" // please notice here
}
}
But I am afraid of the reference (&) will make mistakes.
Is there a better way to do it?