Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP flat array to nested ["a", "b", "c"] to ["a" =>["b"=>["c"]]] [closed]

Tags:

As the title with the example says, I need a flat array to be nested by each following key being the previous value.

Example:

array("I", "need", "this", "to", "be", "nested"); // To: array("I" => array("need" => array("this" => array("to" => array("be" => array("nested")))))) 
like image 521
Dead Man Walker Avatar asked May 21 '15 04:05

Dead Man Walker


People also ask

How do you flatten an array in PHP?

Flattening a two-dimensional arrayarray_merge(... $twoDimensionalArray); array_merge takes a variable list of arrays as arguments and merges them all into one array. By using the splat operator ( ... ), every element of the two-dimensional array gets passed as an argument to array_merge .

What does => mean in PHP array?

=> is the separator for associative arrays. In the context of that foreach loop, it assigns the key of the array to $user and the value to $pass .


1 Answers

Here is a possible implementation:

<?php  function make_nested($array) {     if (count($array) < 2)         return $array;     $key = array_shift($array);     return array($key => make_nested($array)); }  print_r(make_nested(array("I", "need", "this", "to", "be", "nested"))); 

If you don't like recursion, here is an iterative version:

function make_nested($array) {     if (!$array)         return array();     $result = array(array_pop($array));     while ($array)         $result = array(array_pop($array) => $result);     return $result; } 
like image 51
dened Avatar answered Sep 28 '22 00:09

dened