Rob556 Rob556 - 3 months ago 15
PHP Question

Transform flat array to multidimensional with node values

I have an array that looks like this (changed to food for the example - it's actually a taxonomy of business topic tags):

Array
(
[fruit] => Fruit
[fruit/apple] => Apple
[fruit/banana] => Banana
[fruit/passion-fruit] => Passion fruit
[vegetable] => Vegetable
[vegetable/beans] => Beans
[vegetable/beans/runner-beans] => Runner beans
)


I'd like to use recursion (presumably) to change it into this:

Array
(
[fruit] => Array
(
[title] => Fruit
[children] => Array
(
[apple] => Array
(
[title] => Apple
)
[banana] => Array
(
[title] => Banana
)
[passion-fruit] => Array
(
[title] => Passion fruit
)
)
)
[vegetable] => Array
(
[title] => Vegetable
[children] => Array
(
[beans] => Array
(
[title] => Beans
[children] => Array
(
[runner-beans] => Array
(
[title] => Runner beans
)
)
)
)
)
)


I can't figure out how to do it. I've found other examples here for converting flattened arrays into multidimensional ones but not where there's a value ('Title') and a custom child node. Thanks in advance for any pointers.

Answer

Assuming that your array is named $array:

$result = array();

foreach($array as $key => $value) {
    $temp =& $result;
    $path = explode('/', $key);

    foreach($path as $subkey) {
        if(!isset( $temp[$subkey])) {
            $temp[$subkey]['title'] = $value;
            $temp[$subkey]['children'] = array();
        }
        $temp =& $temp[$subkey]['children'];
    }
}

I am posting this even though it creates a children key even when there are no children. I will revisit and edit.

Comments