2014-03-04 157 views
0

我有以下功能:刪除switch語句

private function generateStructureArray($file) { 
    $splitData = explode('/', $file); 
    switch(count($splitData)) { 
    case 1: 
     $this->hierarchy[] = $splitData[0]; 
     break; 
    case 2: 
     $this->hierarchy[$splitData[0]][] = $splitData[1]; 
     break; 
    case 3: 
     $this->hierarchy[$splitData[0]][$splitData[1]][] = $splitData[2]; 
     break; 
    case 4: 
     $this->hierarchy[$splitData[0]][$splitData[1]][$splitData[2]][] = $splitData[3]; 
     break; 
    case 5: 
     $this->hierarchy[$splitData[0]][$splitData[1]][$splitData[2]][$splitData[3]][] = $splitData[4]; 
     break; 
} 

引擎收錄版本:http://pastebin.com/B9vU38nY

我想知道是否有可能去除switch語句此功能,同時還具有相同結果。 $ splitData的大小有時可能超過20,並且20個case switch語句看起來很醜並且錯誤。我對PHP有相當不錯的知識,但到目前爲止,我無法想出一個方法來實現這個功能。

+0

你不能只是做一個foreach超過$ splitData()循環? – 2014-03-04 20:10:23

回答

1

您可以創建這樣使用引用的層級。

private function generateStructureArray($file) { 
    //split the file into paths 
    $splitData = explode('/', $file); 
    //pop off the filename 
    $fileName = array_pop($splitData); 

    //create a temp reference to the hierarchy. Need a temp var 
    //because this will get overwritten again and again. 
    $tmp = &$this->hierarchy; 

    //loop over the folders in splitData 
    foreach($splitData as $folder){ 
     //check if the folder doesn't already exists 
     if(!isset($tmp[$folder])){ 
      //folder doesn't exist so set the folder to a new array 
      $tmp[$folder] = array(); 
     } 
     //re-set tmp to a reference of the folder so we can assign children 
     $tmp = &$tmp[$folder]; 
    } 

    //now we have the folder structure, but no file 
    //if file is not empty, add it to the last folder 
    if(!empty($fileName)){ 
     $tmp[] = $fileName; 
    } 
} 

例子:http://codepad.viper-7.com/laXTVS

+0

喜歡它,謝謝。 – Basaa

0

這樣做是爲了循環。反轉您的數組$ splitData,以便您可以從基本級別構建它並級聯。這樣,通過循環的每次迭代,您可以將層次結構中更下層的元素級聯到當前級別,直到達到頂層。

代碼作爲練習留給讀者

0

這看起來像一個三,你可以使用遞歸... 但是你可以定義一個節點接力將在這種情況下幫助:

class Node { 
    var $Childrens; //array of childrens 
} 

每個節點包含的子陣列

class Three { 
var $root = new Node(); 
} 

,如果你想使用一個hierarchycal結構,你可以使用這個

0

我想每次調用generateStructureArray之前,$ this-> hierarchy都是空數組。你可以簡單地構建陣列與循環:

private function generateStructureArray($file) { 
    $splitData = array_reverse(explode('/', $file)); 
    $result = array(array_pop($splitData)); 
    foreach($splitData as $element) { 
     $result = array($element => $result); 
    } 
    $this->hierarchy = $result; 
}