我更喜欢的方法与此处发布的一些方法非常相似,但并不相同。我在一个受骗的帖子中发现了它:https://stackoverflow.com/a/9546215/4791386 用户“Felix Kling”
他的代码将数组键展平,生成带有点连接键的一维数组,这意味着数值数组将创建自己的“键路径”。这非常有用,但是数组中的大量相似项可能会导致大量无意义的相似路径。
function flatten($array, $prefix = '') {
$result = array();
foreach($array as $key=>$value) {
if(is_array($value)) {
$result = $result + flatten($value, $prefix . $key . '.');
}
else {
$result[$prefix . $key] = $value;
}
}
return $result;
}
在我的例子中,我还需要一个“独特的”路径作为数组键,以及我可以指定的数据样本。所以我扩展了他的方法,添加了一个数字键压缩可选参数。还添加了可选的参数分隔符配置。
主要目的是便于分析关键结构和路径相关数据。我认为当预期任务是键映射以进行进一步的完整数据操作时,此方法很有用。
/**
* Convert a multidimensional array into a single dimension array.
* Nested array keys will be concatenated with the $separator string
* Numeric keys can also be flattened in a "unique key" array style with $numeric_squash
* If $numeric_squash is true, numeric array keys are concatenated with $numeric_squash_separator,
* for later detection and processing if necessary. "[*]" by default.
* If $numeric_squash_separator is set to false, the array key is flattened so that the values
* would be displayed as if there were no numeric array.
*
* array $array : Array to be flattened
* string $prefix : String to prepend on flattened keys
* string $separator : String concatenated between nested array keys.
* bool $numeric_squash : Squash numeric array keys
* string $numeric_squash_separator : String replacing numeric keys, none if false
*/
public static function array_flatten($array, $prefix = '', $separator = '.' , $numeric_squash = false , $numeric_squash_separator = '[*]') {
$result = array();
foreach($array as $key => $value) {
if(is_array($value)) {
if($numeric_squash && is_numeric($key))
$n_key = $numeric_squash_separator ? $numeric_squash_separator . $separator: '';
else
$n_key = $key . $separator;
$result = $result + self::array_flatten($value, $prefix . $n_key , $separator , $numeric_squash , $numeric_squash_separator);
}
else {
$result[$prefix . ($numeric_squash && is_numeric($key) ? '' : $key)] = $value;
}
}
return $result;
}
另外说这个函数没有性能优化,迭代可以保存在 numeric_squash 上,也可以保存一些比较操作。