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

前端 未结 5 1833
悲&欢浪女
悲&欢浪女 2020-12-06 21:17

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

array(
    1=>array(
        2=>array(
            3=>array(
           


        
相关标签:
5条回答
  • 2020-12-06 21:23

    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));
    }
    ?>
    
    0 讨论(0)
  • 2020-12-06 21:32

    You can also use this array library to do that in just one line:

    $array = Arr::setNestedElement([], '1.2.3.4', 'value');
    
    0 讨论(0)
  • 2020-12-06 21:39

    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) {
            }
          }
        } 
      }
    } 
    
    0 讨论(0)
  • 2020-12-06 21:42

    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?

    0 讨论(0)
  • 2020-12-06 21:45
    $x = count($array) - 1;
    $temp = array();
    for($i = $x; $i >= 0; $i--)
    {
        $temp = array($array[$i] => $temp);
    }
    
    0 讨论(0)
提交回复
热议问题