2017-03-20 65 views
1

我試圖把字符串轉換成一個嵌套的數組
這裏是我的字符串:打開字符串嵌套數組PHP

a/b/d.docx 

,我想是這樣的:

array(
    "name" => "a", 
    "type" => "folder", 
    "sub" => array(
     "name" => "b", 
     "type" => "folder", 
     "sub" => array(
      "name" => "c.docx", 
      "type" => "file", 
      "size" => "20" 
     ) 
    ) 
) 

這是我到目前爲止的代碼

$items = explode('/', $strings); 
$num = count($items); 
$num = --$num; 
$temp = array(); 
foreach($items as $keys => $value) { 
    $temp[$keys] = array(
     "name" => $value, 
     "type" => "folder", 
     "items" => $temp[++$keys] 
    ); 
    if($keys == $num){ 
     $temp[$keys] = array(
      "name" => $value, 
      "type" => "file", 
      "size" => "20" 
     ); 
    } 
} 
var_dump($temp); 

我正在嘗試這個功能,但這只是轉動字符串成一個單一的數組,它也不能做'項'線。
任何幫助將不勝感激。謝謝。
請注意,路徑是虛擬的並且不存在。
更新:我如何添加路徑到每個陣列??例如,"path"=>"a/b"

+0

你」我會重新評論一下,我無法追隨你在做什麼以及你想做什麼。 – paullb

+0

'$ num = - $ num'沒用,你可以使用' - $ num'它會是一樣的 –

回答

0
<?php 
$strings='a/b/d.docx'; 

$items = explode('/', $strings); 
$num = count($items)-1; 

$root= array(); 
$cur = &$root; 

$v=''; 

foreach($items as $keys => $value) { 

    $v = $v.$value; 
    $temp = array( "name" => $value, "path"=>$v, "type" => "folder", "items" => ""); 
    if($keys == $num){ 
     $temp = array("name" => $value, "path"=>$v, "type" => "file", "size" => "20"); 
    } 
    $v= $v.'/'; 

    if($keys==0) { 
     $cur = $temp; 
    } 
    else 
    { 
     $cur['items'] = $temp;  
     $cur = &$cur['items']; 
    } 
} 
var_dump($root); 
+0

感謝您的幫助。如何添加路徑到數組?例如」路徑「=>」a/b「 – MRSH

+0

我編輯了我的答案文章,答案很容易理解,您必須親自嘗試學習東西 –

+0

你能解釋一下物品的一部分嗎? – MRSH

2

你可以這樣做:

$path = 'a/b/d.docx'; 

$parts = explode('/', $path); 

$result = [ 'name' => array_pop($parts), 'type' => 'file', 'size' => 20 ]; 

while ($parts) { 
    $result = [ 'name' => array_pop($parts), 'type' => 'folder', 'sub' => $result ]; 
} 

print_r($result); 
+0

感謝您的幫助。如何添加數組的路徑?例如「path」=>「a/b「 – MRSH

0

嘗試遞歸:

public function testAction(){ 
    $sString = 'a/b/c/d.exe'; 
    $aExploded = explode('/', $sString); 
    var_dump($this->_parse_folder_rec($aExploded)); 
} 

private function _parse_folder_rec($aExploded){ 
    $aResult = []; 
    $aResult['name'] = array_shift($aExploded); 
    if($aExploded){ 
     $aResult['type'] = 'folder'; 
     $aResult['sub'] = $this->_parse_folder_rec($aExploded); 
    }else{ 
     $aResult['type'] = 'file'; 
     $aResult['size'] = 20; 
    } 
    return $aResult; 
}