Created
September 6, 2013 17:14
-
-
Save inabhi9/6466810 to your computer and use it in GitHub Desktop.
Expand dotted 2D array to multidimensional array using JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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