doucang8303 2013-01-03 10:43
浏览 27
已采纳

如何从循环创建树状数组?

Suppose I have a one-dimensional array $arr like this:

Array
(
    ['key1'] => 1
    ['key2'] => 1
    ['key3'] => 1
    ['key4'] => 1
)

I want to loop through $arr like this:

foreach($arr as $key => $a) {
   //$tree[????] = ????? Here is my concern
}

such that, doing print_r($tree) produces

Array
(
    ['key1'] => Array
    (
        ['key2'] => Array
        (
            ['key3'] => Array
            (
                ['key4'] => 1
            )
        )
    )
)

My concern is how to increase the dimension (not the values) of the array $tree inside the loop from a single dimension array $numbers such that $tree['key1']['key2']['key3'] is an array and $tree['key1']['key2']['key3']['key4'] is equal to 1.

Furthermore, if I have a single dimensional array $foo with 10 elements. I should produce another array $bar that expands to 10 dimensional array similar to the output above.

What should I do inside the foreach loop? Or instead of using loop, is there a way to produce an output like that of above from a one dimension array?


EDIT:

OK well you obviously need some kind of recursive function, but can you explain how you know that key2 should be a child of key1, key3 should be a child of key2 etc based on the data you show?

The next element of a 1D array is a child of the previous element. So if the 1D array is like this:

Array
(
    ['bar'] => 1 // I don't care of the values as of the moment
    ['foo'] => 1
    ['baz'] => 1
)

Element foo should be the child of bar, and element baz should be the child of foo for the tree array.

Ok so the actual values of everything except the last element are irrelevant?

Actually all values of the 1D array is irrelevant as of this moment. I am only concerned on constructing the tree array.

  • 写回答

2条回答 默认 最新

  • duanjue7745 2013-01-03 11:09
    关注

    The way to do this is to use references.

    function create_tree($arr) {
      $result = array();
      $ref = &$result;
      foreach ($arr as $key => $el) {
        $ref = array($key => $el);
        $ref =& $ref[$key];
      }
      return $result;
    }
    

    How it works:

    $result = array(); // an array to hold the result
    
    $ref = &$result; // start with a reference to the top level
    
    foreach ($arr as $key => $el) { // iterate over the input array
    
      $ref = array($key => $el); // create this level in the array
    
      $ref =& $ref[$key]; // change the reference to be the new deepest level
    
    }
    
    return $result; // return the result
    

    See it working

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境
  • ¥30 关于#java#的问题,请各位专家解答!
  • ¥30 vue+element根据数据循环生成多个table,如何实现最后一列 平均分合并
  • ¥20 pcf8563时钟芯片不启振
  • ¥20 pip2.40更新pip2.43时报错
  • ¥15 换yum源但仍然用不了httpd
  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 麒麟V10 arm安装gdal
  • ¥20 OPENVPN连接问题