Php 尝试从字符串(文件/文件夹结构)创建数组
我有这个字符串:Php 尝试从字符串(文件/文件夹结构)创建数组,php,arrays,recursion,Php,Arrays,Recursion,我有这个字符串: css/ reset.css style.css img/ js/ lib/ jquery.js script.js index.php 我想要那个数组: Array ( [js/] => Array ( [lib/] => Array ( [jquery.js] => )
css/
reset.css
style.css
img/
js/
lib/
jquery.js
script.js
index.php
我想要那个数组:
Array
(
[js/] => Array
(
[lib/] => Array
(
[jquery.js] =>
)
[script.js] =>
)
[index.php] =>
)
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.')) as $entry) {
// do stuff with $entry
}
我写了这段代码:
class Structurer{
public function parse(){
$output = array();
$level = 0;
$currentFolder = '';
function throughtLevels(&$arr, $key, $newKey, $newValue){
if(is_array($arr)){
foreach($arr as $k => $v){
if($k == $key){echo 'ok';
if(is_array($arr[$k])) $arr[$k] = array_merge($arr[$k], array($newKey => $newValue));
else $arr[$k] = array($newKey => $newValue);
}
else throughtLevels($arr[$k], $key, $newKey, $newValue);
}
}
} // throughtLevels
while($this->moveToNextLine()){
$curl = '';
if(preg_match_all('#\t#', $this->currentLine, $n)){
$this->currentLine = str_replace("\t", '', $this->currentLine);
$level = count($n[0]);
}
else $level = 0;
if(preg_match_all('#\[(.*)\]#', $this->currentLine, $com)){
$this->currentLine = str_replace($com[0], '', $this->currentLine);
$curl = implode('', $com[1]);
}
if(preg_match('#\/#', $this->currentLine)){
if($level > 0) throughtLevels($output, $currentFolder, $this->currentLine, array());
else $output[$this->currentLine] = array();
$currentFolder = $this->currentLine;
} else {
if(!empty($this->currentLine)){
if($level > 0)throughtLevels($output, $currentFolder, $this->currentLine, $curl);
else $output[$this->currentLine] = $curl;
}
}
}
echo '<pre>' . print_r($output, 1) . '</pre>';
} // parse(value)
private function moveToNextLine(){
if($this->currentLineNum >= count($this->lines) -1) return false;
$this->currentLine = $this->lines[++$this->currentLineNum];
return true;
} // moveTonextLine
private static function cleanup($value){
$value = str_replace(array("\r\n", "\r"), "\n", $value);
$value = preg_replace('#/\*[^*]*\*+([^/][^*]*\*+)*/#', '', $value);
$value = preg_replace('#^\n#', '', $value);
return $value;
} // cleanup(value)
public function __construct($value){
$this->base = dirname(__FILE__);
$this->currentLineNb = -1;
$this->currentLine = '';
$this->lines = explode("\n", self::cleanup($value));
$this->parse();
} // __construct(value)
private $lines = array();
private $currentLineNum = -1;
private $currentLine = '';
} // Structurer
$input = <<<EOT
css/
reset.css
style.css
img/
js/
lib/
jquery.js
script.js
index.php
EOT;
$arr = new Structurer($input);
我真的不知道怎么解决这个问题。我想我不远,但我不能前进。我建议你看看 要进行线性迭代,请使用:
他不是在目录上迭代,而是在包含目录结构的字符串上迭代。你好,杰克,谢谢你的回答。我看到RecursiveDirectoryIterator使用真正的目录,或者我带了一个常规字符串。。。但是我会检查这个类!:-)你能告诉我为什么你有这样的字符串格式吗?是不是另一个进程的输出超出了您的控制范围?另外,您将如何处理这种输出?
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.')) as $entry) {
// do stuff with $entry
}