Created
February 6, 2012 01:15
-
-
Save abedsujan/1748774 to your computer and use it in GitHub Desktop.
Flatten and Inflate n-dimensional arrays in php
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
private function flatten($array, $base = "", $div_char = "/") | |
{ | |
$ret = array(); | |
if(is_array($array)) | |
{ | |
foreach($array as $k => $v) | |
{ | |
if(is_array($v)) | |
{ | |
$tmp_array = flatten($v, $base.$k.$div_char, $div_char); | |
$ret = array_merge($ret, $tmp_array); | |
} | |
else | |
$ret[$base.$k] = $v; | |
} | |
} | |
return $ret; | |
} |
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
private function inflate($array, $divider_char = "/") | |
{ | |
if( !is_array($arr) ) | |
return false; | |
$split = '/' . preg_quote($divider_char, '/') . '/'; | |
$ret = array(); | |
foreach ($array as $key => $val) | |
{ | |
$parts = preg_split($split, $key, -1, PREG_SPLIT_NO_EMPTY); | |
$leafpart = array_pop($parts); | |
$parent = &$ret; | |
foreach ($parts as $part) | |
{ | |
if (!isset($parent[$part])) | |
$parent[$part] = array(); | |
else if (!is_array($parent[$part])) | |
$parent[$part] = array(); | |
$parent = &$parent[$part]; | |
} | |
if (empty($parent[$leafpart])) | |
$parent[$leafpart] = $val; | |
} | |
return $ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment