Created
April 17, 2018 01:23
-
-
Save V-ed/5b4cf0761f843085b06869a4095cd173 to your computer and use it in GitHub Desktop.
Flattens a multidimensionnal array in PHP mashing the keys together using a parametized separator.
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
/** | |
* Flatten a multi dimension array. For an associative array the child keys are separated by underscore(_) (overwrittable). | |
* | |
* Function taken and tweaked from https://gist.github.com/mmohiudd/7474896 | |
* @author Muntasir Mohiuddin | |
* @param array $a multidimensional array to flatten | |
* @param array &$r multidimensional array to save values | |
* @param string $s separator to use between parent and children keys | |
* @param string $p previous parents separated by the separator | |
* @return array all flattened keys | |
*/ | |
public static function flatten_array($a, &$r, $s = "_", $p = NULL){ | |
$keys = []; | |
foreach($a as $k => $v) { | |
$keys[] = $k; | |
if(is_null($p)){ | |
$_p = $k; | |
} else { | |
$_p = $p . $s . $k; | |
} | |
if (is_array($a[$k])) { | |
$keys = array_merge($keys, self::flatten_array($a[$k], $r, $s, $_p)); | |
} else { | |
$r[$_p] = $v; | |
} | |
} | |
return $keys; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment