将递归目录列表转换为MySQL表

Kev*_*vin 7 php mysql recursion

我需要列出给定父文件夹中的所有文件/文件夹,并将其转储到mysql.

到目前为止,我有:

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$dir = '/home/kevinpirnie/www';

function dirToArray( $dir ) {
    $result = array();
    $cdir = scandir($dir);
    foreach ($cdir as $key => $value) {
        if (!in_array($value, array(".", "..")))  {
            if (is_dir($dir . DIRECTORY_SEPARATOR . $value)){
                $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value);
            } else {
                $result[] = $value;
            }
        }
    }
    return $result;
}

$res = dirToArray($dir);

echo '<hr />';
echo '<pre>';
print_r($res);
echo '</pre>';
Run Code Online (Sandbox Code Playgroud)

我坚持的是如何将ID目录分配给目录,然后将它们与父目录相关联ID.

现在,这段代码完成了我需要的东西,我只需要能够将它转换为mysql插入语句,同时保持关联结构,并且我在长时间的工作中脑力激荡.

最后,我希望有一个类似于以下的表结构:

FileID,FolderID,ParentFolderID,FileName

我怎样才能做到这一点?

php*_*ode 2

我对你的代码做了一些修改。现在对于每个目录,

索引0指向目录索引

索引1指向父目录索引

索引 2,3,....n 指向文件

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$dir = '/home/kevinpirnie/www';

$GLOBALS['I'] = 0; // root folder given index 0

function dirToArray( $dir , $parent) {
    $result = array();
    $cdir = scandir($dir);
    foreach ($cdir as $key => $value) {
        if (!in_array($value, array(".", "..")))  {
            if (is_dir($dir . DIRECTORY_SEPARATOR . $value)){

                $result[$value] = [++$GLOBALS['I']]; // add folder index
                $result[$value][] = $parent; // add parent folder index

                $result[$value][] = dirToArray($dir . DIRECTORY_SEPARATOR . $value, $GLOBALS['I']);
            } else {
                $result[] = $value;
            }
        }
    }
    return $result;
}

$res = dirToArray($dir, $GLOBALS['I']);

echo '<hr />';
echo '<pre>';
print_r($res);
echo '</pre>';
echo '</pre>';
Run Code Online (Sandbox Code Playgroud)

您现在可以使用类似的递归循环将数据直接插入到 mysql 表中(如果您不想使用 mysql 自动生成的 id)

如果你想使用自动生成的mysql id,你应该分两遍插入。在第一遍中插入文件夹数据并从 mysql 插入 id 函数获取 id。然后创建关联数组映射

$array_map[$current_folder_id] = mysqli_insert_id()

然后在第二次递归过程中更新这个id