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

2019-01-20 02:40发布

问题:

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.

回答1:

$x = count($array) - 1;
$temp = array();
for($i = $x; $i >= 0; $i--)
{
    $temp = array($array[$i] => $temp);
}


回答2:

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) {
        }
      }
    } 
  }
} 


回答3:

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));
}
?>


回答4:

I think the syntax for the multidimensional array you want to create would look like the following.

$array = array(

   'array1' => array('value' => 'another_value'), 
   'array2' => array('something', 'something else'),
   'array3' => array('value', 'value')
);

Is this what you're looking for?