Skip to content

Instantly share code, notes, and snippets.

@inabhi9
Created September 6, 2013 17:14
Show Gist options
  • Save inabhi9/6466810 to your computer and use it in GitHub Desktop.
Save inabhi9/6466810 to your computer and use it in GitHub Desktop.
Expand dotted 2D array to multidimensional array using JSON
<?php
function getDottedExpandedArray($array){
$finalArray = array();
foreach ($array as $key => $value) {
$sub_count = substr_count($key, '.')+1;
$json = '{"' . str_replace('.', '" : {"', $key);
$json .= '" : "'.$value.'"'.str_repeat('}', $sub_count);
$array = json_decode($json, true);
$finalArray = array_merge_recursive($finalArray, $array); //Merging array
}
return $finalArray;
}
//Testing
$dotedArray = array(
'fish.in.pond' => 'its there',
'fish.on.tree' => 'Not possible',
'balloon.in.sky' => 'very high',
);
/*
Output: print_r($expandedArray);
Array(
[fish] => Array(
[in] => Array(
[pond] => its there
)
[on] => Array(
[tree] => Not possible
)
)
[balloon] => Array(
[in] => Array(
[sky] => very high
)
)
)
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment