2017-06-21 88 views
0

我有非常複雜的數組,我想爲HTML創建獲取值。如何從PHP中的複雜多維數組中獲取值並將它們轉換爲字符串

我在我的數組中有目錄中的jpg文件列表,但我希望所有來自'materialy-do-plis'目錄的文件都有文件的子目錄,有時甚至更多的子目錄有更多的文件。

我想在foreach數組中獲得一個很好生成的URL,並在目錄名和文件末尾。

這是我的數組怎麼樣子:https://paste.ofcode.org/vE7qBXvGZNDGMSenF9ijST(超長)

這是我的代碼得到它,如果這能幫助:

function pathToArray($path , $separator = '/') { 
    if (($pos = strpos($path, $separator)) === false) { 
     return array($path); 
    } 
    return array(substr($path, 0, $pos) => pathToArray(substr($path, $pos + 1))); 
} 


$dir = APPPATH.'../media/multimedia/obrazy/materialy-do-plis/'; 
$results = array(); 
if (is_dir($dir)) { 
    $iterator = new RecursiveDirectoryIterator($dir); 
    foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) { 
     if ($file->isFile()) { 
      $thispath = str_replace('\\', '/', $file); 
      $thisfile = utf8_encode($file->getFilename()); 
      $results = array_merge_recursive($results, pathToArray($thispath)); 
     } 
    } 
} 
echo "<pre>"; 
print_r($results); 

array_walk($products, function ($value, $key) use ($stores, &$array) { 
    $array[$value['store']][] = $value['product']; 
}); 

print_r($array); 

回答

0

基本上,我想,你需要一個遞歸函數。 該函數可以寫入結果數組,該結果數組可能是一個類變量或通過引用傳入。

基本上是這樣的(未經測試,但得到的想法):

class Foo { 
    private $results = array(); 

    function recurse($inputArray, $path) { 
     foreach($inputArray as $i => $item) { 
      if(is_dir($path."/".$i)) { 
       $this->recurse($item, $path."/".$i); 
      }elseif(is_file($path."/".$item)){ 
       $this->results[] = $path."/".$item; 
      } 
     } 
    } 
} 
+0

我會嘗試一下,謝謝。 – Aksebkit

相關問題