2014-03-04 94 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; 
}