2012-02-25 53 views
0

爲了能夠搜索和索引/排序數組轉換嵌套父/子元素數組大綱編號格式

的緣故,我有我試圖解析一個大型多維數組。現在,我只是使用CakePHP shell來做到這一點,但任何方法都可以。我需要做的,是拿家長/孩子/多生孩子的陣列和創建的ID與關聯的「大綱數字」

因此,例如數組:

1 
1.1 
1.2 
1.2.1 
1.2.2 
1.2.3 

等等。

這裏是我的「輸入數組」的例子:

Array 
(
    [0] => Array 
     (
      [AsapStructure] => Array 
       (
        [id] => 1 
        [lft] => 30267 
        [rght] => 32774 
        [parent_id] => 
        [wbs] => 
       ) 

      [children] => Array 
       (
        [0] => Array 
         (
          [AsapStructure] => Array 
           (
            [id] => 2 
            [lft] => 30268 
            [rght] => 30773 
            [parent_id] => 1 
            [wbs] => 1 
           ) 

          [children] => Array 
           (
            [0] => Array 
             (
              [AsapStructure] => Array 
               (
                [id] => 3 
                [lft] => 30269 
                [rght] => 30382 
                [parent_id] => 2 
                [wbs] => 1.1 
               ) 

我設想的,是有一個簡單的解析機制,是自遞歸什麼。什麼,我開發了一個例子如下:

<?php 
    var $structIndex = array(); 

    private function __parseStruct($toParse,$prefix = null) { 
     $iterator = 0; 
     if ($prefix) 
      $prefix = $prefix . '.'; 

     foreach($toParse as $datum) { 
      $iterator++; 
      if ($datum['AsapStructure']['id'] == 1) 
       $this->structIndex[ 1 ] = NULL; 
      else    
       $this->structIndex[ $datum['AsapStructure']['id'] ] = $prefix . $iterator ; 

      $subiterator = 0; 
      foreach($datum['children'] as $key => $data) { 
       $subiterator++; 
       $this->structIndex[ $data['AsapStructure']['id'] ] = $prefix . $subiterator; 
       if (! empty($datum['children'])) { 
        $this->__parseStruct($datum['children'], $subiterator); 
       } 
      } 
     } 
     return $this->structIndex; 
    } 

?> 

我做什麼,是我把這種$this->__parseStruct($data)功能和數組傳遞給它。該函數然後在數組上循環,調用嵌套子數組的函數。我有那部分工作正常,我似乎無法得到創建'索引'的邏輯正確,即1.1,1.2,1.2.1等等。

所以我的目標輸出然後將:

$array[ $rowid ] = [ 1.1/1.2/1.2.1/1.2.2 ] or any combination as such. 

任何幫助是極大的讚賞。

回答

0

我在正確的軌道上,我只是增加了一個額外的不必要的步驟。

private function __parseStruct($toParse,$prefix = null) { 

    $iterator = 0; 

    if ($prefix) 
     $prefix = $prefix . '.'; 

    foreach($toParse as $datum) { 

     $iterator++; 

     if ($datum['AsapStructure']['id'] == 1) 
      $this->structIndex[ 1 ] = NULL; 
     else    
      $this->structIndex[ $datum['AsapStructure']['id'] ] = $prefix . $iterator ; 



     if (! empty($datum['children'])) { 

      $this->__parseStruct($datum['children'], $prefix.$iterator); 

     } 



    } 

    return $this->structIndex; 

} 

這解決了這個問題。然而,由於我的數組的性質,我必須首先調用函數:$this->__parseStruct($data[0]['children']);否則,我最終以1爲結果數組中的每個數據元素添加前綴。