Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 [duplicate]

Tags:

arrays

php

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.

like image 606
Shijin TR Avatar asked Nov 18 '25 16:11

Shijin TR


2 Answers

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)
like image 102
hsz Avatar answered Nov 20 '25 08:11

hsz


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)

like image 36
Alma Do Avatar answered Nov 20 '25 08:11

Alma Do



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!