2011-08-15 38 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