2012-02-08 87 views
1

我有一個對象 - 我們稱之爲$node屬性的遞歸性

該對象有一個名爲$node->children屬性,它基本上返回子對象(節點)的一個陣列,在node_id => NodeObject形式:

Array 
    [1] => Node object 
    [2] => Node object 
    [3] => Node object 
    ... 

這些子對象是同一類型的,所以它們也具有相同的屬性...

如何收集給定節點的所有子節點和大孩子節點ID?

我需要以某種方式走過所有的孩子節點,但我不知道如何。現在我被困在array_keys($children),但它只讓我成爲一級孩子。

不知道它的問題,但是這個屬性來自於一個神奇的__get方法,我看不出它與print_r的內容...

回答

3
function walknode($node) { 
    //Do some stuff with the node here, e.g. 
    echo "I am working on node $node->name<br>\n"; 

    if (is_array($node->children)) 
    foreach ($node->children as $child) 
     walknode($child); 
} 

walknode($basenode); 
1

如果所有世代的節點具有不同的ID,這應該工作:

$idArray = array(); 
$nodes = $node->children(); 
foreach ($nodes as $pKey => $parent) { 
    array_push($idArray,$pKey); 
    $childNodes = $parent->children(); 
    foreach ($childNodes as $cKey => $child) { 
     array_push($idArray,$cKey); 
    } 
} 
0

當我正確地理解你的問題u得到由鍵列表:

array_keys($node->children) 

爲迭代使用

for ($node->children as $key => $value) { 
    var_dump($key . ' => ' . $value); 
} 
+0

我覺得OP是尋找一個解決方案來遍歷到孫子。 – quickshiftin 2012-02-08 01:26:30

1

嘗試類似如下:

function walkNodes($node, $props = array()) { 

    $props[] = $node->id; 

    if(isset($node->children) && is_array($node->children)){ 
    foreach($node->children as $child) { 
     $props = walkNodes($child, $props); 
    } 
    } 

    return $props; 
} 
1

分配方法的類,這些對象的情況下,像hasChildren。如果在array_keys($ children)的迭代過程中,其中一個子元素返回true,那麼你必須遍歷它。

<?php 

class SomeCollection { 
    public $name; 
    public $children = array(); 

    public function hasChildren() 
    { 
     return !empty($this->children); 
    } 

    public function iterate() 
    { 
     // process children 
     foreach(array_keys($this->children) as $child) { 

      // process grandchildren 
      if($child->hasChildren()) { 
       foreach(array_keys($child->children) as $grandchild) { 
        echo $child . ' is my child & ' . 
         $grandchild . ' is my grandchild!' . PHP_EOL; 
       } 
      } else // process children without grandchildren 
       echo $child . ' is my child of mine with no children of his own!'; 
     } 
    } 
} 

如果你想探索一些內置工具檢出SPL Iterators

+0

回想起來,這不是一個遞歸解決方案!我仍然認爲它很有用,因爲它顯示了使用hasChildren()函數抽象底層數組的價值。一個更完整的例子也會提供getChildren(),但是我會留給SPL等讀者。 – quickshiftin 2012-02-08 02:56:32