2013-06-03 324 views
1

我使用PHP工作。我有一個數組,這樣做:(level屬性是分支的樹我想要的水平)從一個數組中創建一個「樹型數組」php

Array (
    [0] => stdClass Object 
      (
        [value] => Array 
          (
            [name] => Dog 
            [level] => 1 
          ) 
      ) 
    [1] => stdClass Object 
      (
        [value] => Array 
          (
            [name] => Yorkshire 
            [level] => 2 
          ) 
      ) 

    [2] => stdClass Object 
      (
        [value] => Array 
          (
            [name] => Rottweiler 
            [level] => 2 
          ) 
      ) 

    [3] => stdClass Object 
      (
        [value] => Array 
          (
            [name] => Cat 
            [level] => 1 
          ) 
      ) 
) 

我的目標是做出某種樹陣,從它,像這樣:

Array (
    [0] => stdClass Object 
      (
        [value] => Array 
          (
            [name] => Dog 
            [level] => 1 
          ) 
      ) 

      Array (

        [1] => stdClass Object 
          (
            [value] => Array 
              (
                [name] => Yorkshire 
                [level] => 2 
              ) 
          ) 

        [2] => stdClass Object 
          (
            [value] => Array 
              (
                [name] => Rottweiler 
                [level] => 2 
              ) 
          ) 

    ) 

    [3] => stdClass Object 
      (
        [value] => Array 
          (
            [name] => Cat 
            [level] => 1 
          ) 
      ) 
) 

但我真的無法做到這一點。我甚至有問題看到算法! 任何幫助將不勝感激。

+0

你需要某種形式的ID告訴你誰是這個孩子的父母。因爲我知道lvl,但我不知道這個lvl 2屬於哪一個lvl。 – Guerra

+0

我也想過這個,但樹已經「訂購」了。我的意思是說到這樣的: 1級 級11 水平12 2級 3級 級31 水平32 – Franck

+0

瞭解,如果你能保持這個順序跳投您的解決方案將是還挺:(看答案) – Guerra

回答

0

我設法做這種方式:

$new = array(); 
foreach ($arr as $a){ 
    $new[$a['parentid']][] = $a; 
} 
$tree = createTree($new, $new[0]); // changed 
print_r($tree); 

function createTree(&$list, $parent){ 
    $tree = array(); 
    foreach ($parent as $k=>$l){ 
     if(isset($list[$l['id']])){ 
      $l['children'] = createTree($list, $list[$l['id']]); 
     } 
     $tree[] = $l; 
    } 
    return $tree; 
} 

亞瑟:create array tree from array list

1
$treelist = array(); 
foreach($list as $key=>$l){ 
    if($l['level'] == 1){ 
     $l['childs'] = array(); 
     $treelist[] = $l; 
    }else{ 
     $treelist[count($treelist-1)]['childs'][] = $l; 
    } 
} 

類似的東西