Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I invert a multi-dimensional array?

I have an array with n elements in it, with each element containing n child elements, each containing...

Array
(
    [tea] => Array
        (
            [drink] => Array
                (
                    [food] => 
                )
        )
    [biscuits] => Array
        (
            [snack] => Array
                (
                    [food] => 
                )
        )
    ...
)

What I want to do is have the inner most element on the outside, and the outer most elements on the inside:

Array
(
    [food] => Array
        (
            [drink] => Array
                (
                    [tea] => 
                )
            [snack] => Array
                )
                    [biscuits] => 
                (
        )
    ...
)

And the solution needs to be able to deal with n children arrays. I am aware of How do I invert a multidimensional array in PHP but the solutions there did not solve this problem.

like image 553
Richard Parnaby-King Avatar asked May 13 '26 20:05

Richard Parnaby-King


1 Answers

I'm pretty sure this could be condensed further, but it does the job:

function flatten(array $array) {
    $key = array(key($array));
    $val = current($array);
    if (is_array($val)) {
        $key = array_merge(flatten($val), $key);
    }
    return $key;
}

function build(array $path, array $result) {
    $key = array_shift($path);
    if (!isset($result[$key])) {
        $result[$key] = $path ? array() : null;
    }
    if ($path) {
        $result[$key] = build($path, $result[$key]);
    }
    return $result;
}

$result = array();
foreach ($array as $key => $value) {
    $result = build(flatten(array($key => $value)), $result);
}

Demo: http://codepad.org/rnZPdWGG

like image 138
deceze Avatar answered May 15 '26 09:05

deceze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!