Flatten array

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
public function array_flatten($a, $f = array()) {
    if (!$a || !is_array($a)) {
        return '';
    }
    if (is_array($a) && count($a)) {
        foreach ($a as $k => $v) {
            if (is_array($v)) {
                $f = mslib_befe::array_flatten($v, $f);
            } else {
                $f[$k] = $v;
            }
        }
    }
    return $f;
}

If you want to keep the prefix of the parent key then use:

function array_flatten($array, $prevKey = '') {
	if (!is_array($array)) {
		return FALSE;
	}
	$result = array();
	foreach ($array as $key => $value) {
		if (is_array($value)) {
			$result = array_merge($result, self::array_flatten($value, $key));
		}
		else {
			if ($prevKey) {
				$keyName=$prevKey . '[' . $key.']';
			} else {
				$keyName=$key;
			}
			$result[$keyName] = $value;
		}
	}
	return $result;
}
Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp