0

I have a multidimensional array of arrays (source below), where my keys and values are arbitrary strings. I want to create a new array (desired below), where the hierarchy stays the same, but every KEY is restructured into its own array, with the key itself becoming a 'title' value, and any subarrays are continued under 'children'.

How can I accomplish this using a recursive function that takes &$source and &$destination arrays, and populates the destination array accordingly?

Source Array:

Array (
    [Alpha] => Array (
        [Red] => one
        [Blue] => two
    )
    [Bravo] => Array (
        [Blue] => three
    )
)

Desired Array:

Array (
    [0] => Array (
        [title] => Alpha
        [children] => Array (
                    [0] Array([title] => Red, [children]= > false)
                    [1] Array([title] => Blue, [children]= > false)
        )
    )
    [1] => Array (
        [title] => Bravo
                    [0] Array([title] => Blue, [children]= > false)
        )
    )
)

Note: I don't care about the final nodes/leafs in my new array.

2 Answers 2

3

You can do te conversion without passing a reference to the destination array.

function convert_array($from){
    if(!is_array($from)){
        return false;
    }
    $to = array();
    foreach($from as $k=>$v){
        $to[] = array(
            'title' => $k,
            'children' => convert_array($v)
        );
    }
    return $to;
}

Codepad example

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, works great. BTW what is the significance of using $to[] versus just $to in the foreach? Only $to[] seems to work, but $to is still ok syntax-wise.
Using $to[] you are appending an element to the array (the same as using array_push), using $to you are overwriting the array each time.
1

I have programmed array recursively.

$a = array(
    'Alpha' => array('Red' => 'one', 'Blue' => 'two'),
    'Bravo' => array('Blue' => 'three'));


function copyarray($datas){
    $arr = array();

            if(is_array($datas)){
                foreach($datas as $key => $val){
                    if(is_array($val)){
                    $arr[$key] = copyarray($val);
                    }else
                    $arr[$key]=$val;
                }
            }
            return $arr;
}

echo "<pre>";print_r(copyarray($a));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.