下記のようなCSVからPHPでファイルツリーを作りたいと思っております。
この記事を参考に書いたのですが、何も表示されませんでした。
フォルダ1 | フォルダ2 | ファイル名 | リンク |
---|---|---|---|
Folder01 | FolderA | File01 | http://example.com/folder01/folderA/file01.jpg |
Folder01 | FolderA | File02 | http://example.com/folder01/folderA/file02.jpg |
Folder02 | File03 | http://example.com/folder02/file03.jpg |
表示したい内容
HTML
1<ul> 2 <li> 3 Folder01 4 <ul> 5 <li>FolderA 6 <ul> 7 <li> 8 <a href="http://example.com/folder01/folderA/file01.jpg">File01</a> 9 </li> 10 <li> 11 <a href="http://example.com/folder01/folderA/file02.jpg">File02</a> 12 </li> 13 </ul> 14 </li> 15 </ul> 16 </li> 17 <li> 18 Folder02 19 <ul> 20 <li> 21 <a href="http://example.com/folder02/file03.jpg">File03</a> 22 </li> 23 </ul> 24 </li> 25</ul>
表示イメージ
- Folder01 - FolderA - File01 - File02 - Folder02 - File03
現状のPHP
PHP
1<?php 2//variables 3$file = 'list.csv'; 4$all_rows = []; 5$new = []; 6$tofind = []; 7$header = null; 8 9//function 10function createTree(&$list, $parent){ 11 $tree = array(); 12 foreach ($parent as $k=>$l){ 13 if(isset($list[$l['code']])){ 14 $l['children'] = createTree($list, $list[$l['code']]); 15 } 16 $tree[] = $l; 17 } 18 return $tree; 19} 20 21 22//parsing CSV 23$f = fopen($file, "r"); 24$size = filesize($file) + 1; 25while ($row = fgetcsv($f, $size, ",")) { 26 if ($header === null) { 27 $header = $row; 28 continue; 29} 30 $all_rows[] = array_combine($header, $row); 31} 32 33 34foreach ($all_rows as $a){ 35 $new[$a['parent']][] = $a; 36} 37//Get all root parent id 38$keys = array_keys(array_column($all_rows, 'parent'), ''); 39 40foreach ($keys as $key){ 41 $tofind[]= $all_rows[$key]; 42} 43 44print_r($tofind); 45 46//Tree 47$tree = createTree($new, $tofind); 48?>
回答2件
あなたの回答
tips
プレビュー