Shijin TR
Shijin TR

Reputation: 7768

Convert a flat array of values into an associative nested array and use the last value from the input as the last value in the output

I have an array like,

Array
(
    [0] => controllers
    [1] => event
    [2] => add_new_file.php
)

I want to change it like

Array([controllers]=>[event]=>add_new_file.php)

Is there any idea about to change like this,Anyone have idea to change like this.

Upvotes: 3

Views: 210

Answers (2)

Alma Do
Alma Do

Reputation: 37365

While combination of array_reverse() and cycle will do the stuff, I was to late to post that (see good answer with that). So, this answer is just kind of joke (since I was curious - is it possible to resolve a matter with one-liner)

$rgData   = ['foo', 'bar', 'baz'];
eval('$rgResult["'.join('"]["', array_slice($rgData, 0, -1)).'"] = "'.array_pop($rgData).'";');
//var_dump($rgResult);

(normally, never use eval - but it's academic interest, nothing more)

Upvotes: 1

hsz
hsz

Reputation: 152216

Try with:

$input  = array('controllers', 'event', 'add_new_file.php');
$output = null;

foreach (array_reverse($input) as $value) {
  if (is_null($output)) {
    $output = $value;
  } else {
    $output = array($value => $output);
  }
}

Output:

array (size=1)
  'controllers' => 
    array (size=1)
      'event' => string 'add_new_file.php' (length=16)

Upvotes: 6

Related Questions