Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a nested array out of an array in PHP

Say, we have an array: array(1,2,3,4,...) And I want to convert it to:

array(
    1=>array(
        2=>array(
            3=>array(
                4=>array()
            )
        )
    )
)

Can anybody help?
Thanks

EDIT It would be good to have the solution with iterations.

like image 895
MrFix Avatar asked Jun 19 '13 10:06

MrFix


3 Answers

$x = count($array) - 1;
$temp = array();
for($i = $x; $i >= 0; $i--)
{
    $temp = array($array[$i] => $temp);
}
like image 169
Gregor Menih Avatar answered Sep 25 '22 15:09

Gregor Menih


You can simply make a recursive function :

<?php
function nestArray($myArray)
{
    if (empty($myArray))
    {
        return array();
    }

    $firstValue = array_shift($myArray);
    return array($firstValue => nestArray($myArray));
}
?>
like image 45
Blackhole Avatar answered Sep 22 '22 15:09

Blackhole


Well, try something like this:

$in  = array(1,2,3,4); // Array with incoming params
$res = array();        // Array where we will write result
$t   = &$res;          // Link to first level
foreach ($in as $k) {  // Walk through source array
  if (empty($t[$k])) { // Check if current level has required key
    $t[$k] = array();  // If does not, create empty array there
    $t = &$t[$k];      // And link to it now. So each time it is link to deepest level.
  }
}
unset($t); // Drop link to last (most deep) level
var_dump($res);
die();

Output:

array(1) {
  [1]=> array(1) {
    [2]=> array(1) {
      [3]=> array(1) {
        [4]=> array(0) {
        }
      }
    } 
  }
} 
like image 43
Bogdan Burym Avatar answered Sep 23 '22 15:09

Bogdan Burym