我有以下功能:
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;
}
Pastebin-version:http://pastebin.com/B9vU38nY
我想知道是否可以删除此函数的switch语句,同时仍然具有相同的结果。 $ splitData的大小有时可能超过20,并且20个案例的switch语句看起来很丑陋和错误。我对PHP有很好的了解,但到目前为止,我还没有想到一种方法来实现这个功能。
答案 0 :(得分: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;
}
}
答案 1 :(得分:0)
将此作为for循环。反转你的数组$ splitData,以便你可以从基础级别构建它并级联。这样,通过循环的每次迭代,您可以将层次结构中较低级别的元素级联到当前级别,直到达到顶部。
将代码作为练习留给读者
答案 2 :(得分:0)
这看起来像三个,你可以使用递归... 但是你可以定义一个节点oop在这种情况下会有所帮助:
class Node {
var $Childrens; //array of childrens
}
每个Node包含一个子数组
class Three {
var $root = new Node();
}
如果你想使用一个层次结构
,你可以使用它答案 3 :(得分:0)
我想$ this->层次结构在每次调用generateStructureArray之前都是空数组。你可以简单地用for循环构造数组:
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;
}