/** * Take a multidimensional array and return a singledimensional one * Array keys are concatenated by "." * @param array $array * @param string $prefix Prefix the array key * @param string $glue * @return array */ function flattenArray(array $array, $prefix = "", $glue = '.') { $result = []; foreach ($array as $key => $value) { if (is_array($value)) { $result = array_merge($result, flattenArray($value, $prefix . $key . $glue)); } else { $result[$prefix . $key] = $value; } } return $result; }
function flattenArray(array $array, $join = '/') { $oneDimArray = array(); foreach ($array as $key => $value) { if (is_array($value)) { $flatValues = flattenArray($value, $join); foreach ($flatValues as $subKey => $subValue) { $oneDimArray[$key . $join . $subKey] = $subValue; } } else { $oneDimArray[$key] = $value; } } return $oneDimArray; }
function flattenArray($subarray) { $keys = @array_keys($subarray); for ($i = 0; $i < count($keys); $i++) { if (is_array($subarray[$keys[$i]])) { flattenArray($subarray[$keys[$i]]); } else { $GLOBALS["tmp"]["flattenArray"][$keys[$i]] = $subarray[$keys[$i]]; } } }
function flattenArray($array, $prefix = '') { # Start with empty array $stack = array(); # Loop through the array to flatten foreach ($array as $key => $value) { # Decode the input name $key = inputDecode($key); # Determine what the new key should be - add the current key to # the prefix and surround in [] $newKey = $prefix ? $prefix . '[' . $key . ']' : $key; if (is_array($value)) { # If it's an array, recurse and merge the returned array $stack = array_merge($stack, flattenArray($value, $newKey)); } else { # Otherwise just add it to the current stack $stack[$newKey] = clean($value); } } # Return flattened return $stack; }
function flattenArray($array) { $flatArray = array(); foreach ($array as $subElement) { if (is_array($subElement)) { $flatArray = array_merge($flatArray, flattenArray($subElement)); } else { $flatArray[] = $subElement; } } return $flatArray; }
<?php $a = array(1, 2, array(array(3 => array(4, array(5)))), array(6, 7, 8), array(9, '{10}')); echo implode(' ', flattenArray($a)) . PHP_EOL; function flattenArray($arr) { $outputArr = array(); while (!empty($arr)) { $e = array_shift($arr); if (!is_array($e)) { $outputArr[] = $e; } else { foreach (array_reverse($e) as $se) { array_unshift($arr, $se); } } } return $outputArr; }
public function testFlattenArray() { $multi = ['a' => 'b', 'c' => ['d' => 'e', 'f' => ['g' => 'h']]]; $single = ['a' => 'b', 'c.d' => 'e', 'c.f.g' => 'h']; $this->assertEquals($single, flattenArray($multi)); }