I created a PHP function that will convert an array:
[
'one/two' => 3,
'one/four/0' => 5,
'one/four/1' => 6,
'one/four/2' => 7,
'eight/nine/ten' => 11,
]
Into the following JSON string:
{
"one":
{
"two": 3,
"four": [ 5,6,7]
},
"eight":
{
"nine":
{
"ten":11
}
}
}
Here is the function:
<?php
function toJsonStr($array) {
$final_array = [];
foreach ($array as $key => $value) {
$key_exploded = explode("/", $key);
$array_index_at_end = is_numeric(end($key_exploded)) ? true : false ;
if ($array_index_at_end === true) {
$array_index = array_pop($key_exploded);
}
$ref = &$final_array;
foreach ($key_exploded as $value2) {
if (!isset($ref[$value2])) {
$ref[$value2] = [];
}
$ref = &$ref[$value2];
}
if ($array_index_at_end === true) {
$ref[$array_index]=$value;
} else {
$ref=$value;
}
}
return json_encode($final_array);
}
$array = [
'one/two' => 3,
'one/four/0' => 5,
'one/four/1' => 6,
'one/four/2' => 7,
'eight/nine/ten' => 11,
];
$json_str = toJsonStr($array);
echo "\n";
print_r($json_str);
echo "\n\n";
I'm almost positive that this can also be done recursively. I am new to recursion and am having trouble structuring an approach when creating a recursive version.
Would it even be worthwhile to create a recursive version? Maybe it would be too difficult to understand compared to the simple foreach within a foreach I have implemented above?
I know that recursive algorithms simplify and make code more compact but in this case would it be worth it?