2

Say I have this as a PHP array

$my = array('Google','Api','Key');

How can I create a nested array so it ends up like this

$new = array('Google'=>array('Api'=>array('key'=>'Some Value');

It needs to be dynamic as I will have no idea how many elements $my holds.

I have spent 8 hours trying and failed any help would be appreciated.

I have edited this as I need the final element in the $my array to have a value set. How would I do this.

Thanks

1
  • To be honest Matt I have tried so many things I have got myself all confussed. My head tells me I need to use recursion. The trouble I am having is getting the previous arrays I have added. I seem to always end up with a 1 dimensional array Commented Feb 26, 2012 at 3:36

1 Answer 1

4
function build_recursive_array($array)
{
    if(sizeof($array) < 1) return array();

    $key = array_shift($array);
    return array($key => build_recursive_array($array));
}
print_r(build_recursive_array(array('Google','Api','Key')));
6
  • +1 | Well done, in before me. ;P I used empty() rather than sizeof() though. Commented Feb 26, 2012 at 3:39
  • Alex, how would I add a value to the last element in the $my array. Thanks Commented Feb 26, 2012 at 4:47
  • @Chris The line that says return array() is Key's value. You can change that. Commented Feb 26, 2012 at 4:51
  • @Kristian Antonsen , but how do I know it is the last element in the array ? Would I yet the count of $my and use an if statement so when it's on the last element to not do build_recursive_array($array) but $key => "Some Value" Commented Feb 26, 2012 at 5:00
  • @Chris That line only returns if it is the last element. Just change it to if(sizeof($array) < 1) return 'Some Value'; and you'll be good. Commented Feb 26, 2012 at 5:02

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.