Chris
Chris

Reputation: 23

Create a PHP nested array from array with unknown number of values

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

Upvotes: 2

Views: 274

Answers (1)

Alex
Alex

Reputation: 12039

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')));

Upvotes: 4

Related Questions