PHP创建递归文件结构

时间:2018-12-05 06:14:04

标签: php laravel

我正在使用php Web应用程序,并且需要基于具有以下结构的mysql表创建文件结构:

hadoop fs -put /home/cloudera/Desktop/dealer/plantoutput/* /tabplant

因此,“父级”列指向同一表的“ Id”,并且我具有用于递归创建的下一个php函数,但无法按我的意愿工作:

+---------------------------------------+
| tPages                                |
+----+-----------------+-------+--------+
| Id | PageName        | IsDir | Parent | 
+----+-----------------+-------+--------+
| 1  | Index           | 0     | 0      |
+----+-----------------+-------+--------+
| 2  | Dir1            | 1     | 0      |
+----+-----------------+-------+--------+
| 3  | Sub1            | 1     | 2      |
+----+-----------------+-------+--------+
| 4  | Page1_in_Sub1   | 0     | 3      | 
+----+-----------------+-------+--------+
| 5  | Page_in_Dir1    | 0     | 2      |
+----+-----------------+-------+--------+
| 6  | Page2_in_Sub1   | 0     | 3      |
+----+-----------------+-------+--------+

当我将结果集传递给“递归”功能时,请帮助我,这将在最后一个目录中创建文件。谢谢。

1 个答案:

答案 0 :(得分:0)

与其执行重复的SQL查询,不如依靠一次加载所有数据并对其进行处理。假定数据是有序的(例如,在创建文件时,其所在目录已在列表中。

// Test data
$pages = [(object)["Id" => 1, "PageName" => "p1", "IsDir" => 0, "Parent" => 0],
    (object)["Id" => 2, "PageName" => "d1", "IsDir" => 1, "Parent" => 0],
    (object)["Id" => 3, "PageName" => "p2", "IsDir" => 0, "Parent" => 2]
];

// Work out the path for an entry.
// Change $basePath to be the path you need to start the structure in.
// (No trailing /)
function getPath ( $page, $pagesIndex, $basePath = 'faq' ) {
    if ( $page->Parent == 0 )   {
        $path = $basePath."/";
        if ( $page->IsDir == 1) {
            $path .= $page->PageName;
        }
    }
    else    {
        $path = $pagesIndex[$page->Parent]->path;
    }
    return $path;
}

// Re-index the data so that the Id is the index into the array
$pagesIndex = array_column($pages, null, "Id");
foreach ( $pagesIndex as $page ) {
    if ( $page->IsDir == 1 )    {
        $path = getPath($page, $pagesIndex);
        // If directory doesn't already exist - create it
        if (!file_exists($path) && !is_dir($path)) {
            mkdir ( $path );
        }
        // Store the path in the object so that sub folders/files know where to start
        $page->path = $path;
    }
    else    {
        // code for create the file:
        $html = "some html";
        // Make sure the path is part of the filename to be creates
        $myFile = getPath($page, $pagesIndex)."/".$page->PageName.'.html'; // or .php
        $fh = fopen($myFile, 'w') or die("error");
        fwrite($fh, $html);
        fclose($fh);}
}