note 94383 deleted from function.array-values by crell
| From: | crell@php.net | Date: | Tue, 12 Apr 2022 01:04:25 +0000 |
| Subject: | note 94383 deleted from function.array-values by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-218181@lists.php.net to get a copy of this message | ||
Note Submitter: Carsten Milkau
----
Note that in a multidimensional array, each element may be identified by a _sequence_ of keys, i.e.
the keys that lead towards that element. Thus "preserving keys" may have different
interpretations. Ivan's function for example creates a two-dimensional array preserving the
last two keys. Other functions below create a one-dimensional array preserving the last key. For
completeness, I will add a function that merges the key sequence by a given separator and a function
that preserves the last n keys, where n is arbitrary.
<?php
/*
* Flattening a multi-dimensional array into a
* single-dimensional one. The resulting keys are a
* string-separated list of the original keys:
*
* a[x][y][z] becomes a[implode(sep, array(x,y,z))]
*/
function array_flatten_sep($sep, $array) {
$result = array();
$stack = array();
array_push($stack, array("", $array));
while (count($stack) > 0) {
list($prefix, $array) = array_pop($stack);
foreach ($array as $key => $value) {
$new_key = $prefix . strval($key);
if (is_array($value))
array_push($stack, array($new_key . $sep, $value));
else
$result[$new_key] = $value
}
}
return $result;
}
/*
* Flattening a multi-dimensional array into an
* n-dimensional one. The last n keys of each element are
* preserved. If this results in ambiguities, results are
* undefined.
*
* a[x_1][x_2]...[x_m] becomes a[x_{m-n+1}]...[x_m]
*/
function array_flatten_n($array, $n) {
$result = array();
$stack = array();
array_push($stack, array(array(), $array));
while (count($stack) > 0) {
list($prefix, $array) = array_pop($stack);
foreach ($array as $key => $value) {
if (is_array($value)) {
$new_prefix = array_values($prefix);
array_push($new_prefix, $key);
if (count($new_prefix) >= n)
array_shift($new_prefix);
array_push($stack, array($new_prefix, $value));
} else {
$array = $result;
foreach ($prefix as $pkey) {
if (!is_array($array[$pkey]))
$array[$pkey] = array();
$array = $array[$pkey];
}
$array[$key] = $value;
}
}
}
return $result;
}
?>