Created
November 8, 2011 07:48
-
-
Save thoov/1347245 to your computer and use it in GitHub Desktop.
Flatten and Inflate n-dimensional arrays in php.
This file contains hidden or 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 | |
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 hidden or 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 | |
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