Alen Alen - 3 months ago 8
PHP Question

Generate multidimensional array out of exploded string

I'm stuck at generating multidimensional array out of string and I need your help.
This is the string (json):

{
"API_OVERVIEW" : "Overview",
"API_OVERVIEW_CON1" : "API v1 offers a simple REST API to retrieve information about our markets. The API responses are JSON encoded arrays. Please be aware that calls to the API are rate limited to 10 requests per second, any requests exceeding this rate will be met with a HTTP 503 response.",
"API_REFERENCE" : "API Reference",
"API_MARKET_SUMMARY" : "Market Summary",
"API_MARKET_STATS" : "Market Stats",
"API_MARKET_TRADES" : "Market Trades",
"API_MARKET_ORDERS" : "Market Orders",
"API_MARKET_CHARTDATA" : "Market Chart Data",
}


Now I need to explode the
key
by "_" and convert it to multidimensional array, then at the end I need to set the value.
Output should be like this:

"API" =>
[
"MARKET" =>
["SUMMARY" => "Market Summary"],
["STATS" => "Market STATS"]
...
]
"ANOTHER STRING" =>
[
....
]


Currently I get this:

array(1) {
["API"]=>
array(1) {
["MARKET"]=>
array(1) {
["SUMMARY"]=>
string(14) "Market Summary"
}
}
}
[8]=>
array(1) {
["API"]=>
array(1) {
["MARKET"]=>
array(1) {
["STATS"]=>
string(12) "Market Stats"
}
}
}...


This is my code:

$results = [];
foreach($data as $key => $value){
$result = [];
$exploded = explode('_', $key);
$path = &$result;

$counter = 1;
foreach($exploded as $explodedpart){
if(!array_key_exists($explodedpart, $path)){
if($counter == count($exploded)){
$path[$explodedpart] = $value;
}else{
$path[$explodedpart] = array();
}
}
$path = &$path[$explodedpart];

$counter++;
}

array_push($results, $result);
}

return $results;


Idea taken from this answer: http://stackoverflow.com/a/8993400/1672261

Answer

In your code instead of array_push($results, $result); replace with $results = array_merge_recursive($results, $result);

The results will be

{
   "API":{
      "OVERVIEW":{
         "0":"Overview",
         "CON1":"API v1 offers a simple REST API to retrieve information about our markets. The API responses are JSON encoded arrays. Please be aware that calls to the API are rate limited to 10 requests per second, any requests exceeding this rate will be met with a HTTP 503 response."
      },
      "REFERENCE":"API Reference",
      "MARKET":{
         "SUMMARY":"Market Summary",
         "STATS":"Market Stats",
         "TRADES":"Market Trades",
         "ORDERS":"Market Orders",
         "CHARTDATA":"Market Chart Data"
      }
   }
}

As you see not sure how do you want to handle API_OVERVIEW & API_OVERVIEW_CON1. But I hope this will help you in some way.

Also tried something different. This also outputs the same results

$results = array();

foreach($data as $key => $value) {
    // Get all the keys
    $keyParts = explode('_', $key);

    // Make a JSON string
    // Like this {"A" : { "B" : "c" } }
    $jsonStr = '{"'; // Open brackets
    $jsonStr .= implode('":{"', $keyParts);
    $jsonStr .= '":"'.$value.'"'; // End of the str

    // Close brackets
    // No of close brackets = No of keys
    for($i = 0; $i < count($keyParts); $i++) {
        $jsonStr .= "}";
    }

    // Convert the JSON string into array
    $tmpResults = json_decode($jsonStr, true);

    // Merge into final results
    $results = array_merge_recursive($results, $tmpResults);
}