2011-08-15 42 views
3

我想问问如何转换阵列象下面这样:转换阵列结构()笨帮手

$arr = array(
    array(
     'id' => 1, 
     'name' => 'Home', 
     'link_to' => 'home.php', 
     'parent' => 0, 
     'level' => 1 
    ), 
    array(
     'id' => 2, 
     'name' => 'About', 
     'link_to' => 'about.php', 
     'parent' => 0, 
     'level' => 1 
    ), 
    array(
     'id' => 3, 
     'name' => 'About Me', 
     'link_to' => 'about-me.php', 
     'parent' => 2, 
     'level' => 2 
    ), 
    array(
     'id' => 4, 
     'name' => 'About Us', 
     'link_to' => 'about-us.php', 
     'parent' => 2, 
     'level' => 2 
    ), 
    array(
     'id' => 5, 
     'name' => 'Contact Us', 
     'link_to' => 'contact-us.php', 
     'parent' => 4, 
     'level' => 3 
    ), 
    array(
     'id' => 6, 
     'name' => 'Blog', 
     'link_to' => 'blog.php', 
     'parent' => 0, 
     'level' => 1 
    ), 
); 

到这一个:

$result = array(
    'Home', 
    'About' => array(
     'About Me', 
     'About Us' => array(
      'Contact Us' 
     ) 
    ), 
    'Blog' 
); 

有元素“父” ID这可以告诉父数组(0 = root),并且还有元素'level'。

我需要那种数组,所以我可以使用codeigniter helper中的ul()函数创建列表。

+0

这是非常简单的,你自己尝试过的东西? – J0HN

+0

你应该拼出整个数组,因为一些新元素之间的关系不太明显。看起来你想用键翻转一些值,你可以使用'array_flip'作为http://www.php.net/manual/en/function.array-flip.php – Chamilyan

回答

1

我不得不做类似的事情来从数据行创建一棵树。

所以,你必须使用引用,它比其他方式更容易。

下一个代码到达类似你想要什么(我认为这是更好的结构,如果你进行了更改后)

<?php 

    $arr = array(
     array(
      'id' => 1, 
      'name' => 'Home', 
      'link_to' => 'home.php', 
      'parent' => 0, 
      'level' => 1 
     ), 
     array(
      'id' => 2, 
      'name' => 'About', 
      'link_to' => 'about.php', 
      'parent' => 0, 
      'level' => 1 
     ), 
     array(
      'id' => 3, 
      'name' => 'About Me', 
      'link_to' => 'about-me.php', 
      'parent' => 2, 
      'level' => 2 
     ), 
     array(
      'id' => 4, 
      'name' => 'About Us', 
      'link_to' => 'about-us.php', 
      'parent' => 2, 
      'level' => 2 
     ), 
     array(
      'id' => 5, 
      'name' => 'Contact Us', 
      'link_to' => 'contact-us.php', 
      'parent' => 4, 
      'level' => 3 
     ), 
     array(
      'id' => 6, 
      'name' => 'Blog', 
      'link_to' => 'blog.php', 
      'parent' => 0, 
      'level' => 1 
     ), 
    ); 


    $refs = array(); 

    foreach($arr as &$item) { 
     $item['children'] = array(); 
     $refs[$item['id']] = $item; 
    } 

    unset($item); // To delete the reference 

    // We define a ROOT that is the top of each elements 
    $refs[0] = array(
     'id' => 0, 
     'children' => array() 
    ); 

    foreach($arr as $item) { 
     if($item['id'] > 0) { 
      $refs[$item['parent']]['children'][] = &$refs[$item['id']]; 
     } 
    } 

    $result = $refs[0]; 

    unset($refs); // To delete references 

    var_dump($result); 

?> 
+0

谢谢,它的工作原理。感谢您指出foreach循环中引用的用法。 – Permana