我正在尝试使用递归函数将mysql表转换为POO数组以获取所有目录并将它们推送到每个目录中。但是我有一些实现问题,因为我的代码不起作用(只有一半)。我编辑了一些代码,因为它很长(对于stackoverflow帖子)所以如果缺少某些东西警告我。
示例文件夹表:
id | parent_id | foldername
1 | 0 | folder1
2 | 0 | folder2
3 | 1 | folder3
4 | 2 | folder4
5 | 3 | folder5
示例文件表:
id | folderid | filename | filepath
1 | 1 | file1 | serverpath
2 | 1 | file2 | serverpath
3 | 2 | file3 | serverpath
4 | 5 | file4 | serverpath
5 | 4 | file5 | serverpath
folderid引用文件夹表中的id
我的PHP课程:
class Root
{
public $root = array();
public function __construct($object)
{
$this->root = $object;
}
}
class Folder
{
public $folderid;
public $foldername;
public $files = array();
public $folders = array();
public function __construct($folderid, $foldername)
{
$this->folderid = $folderid;
$this->foldername = $foldername;
}
public function addFile($file)
{
if ($file instanceof File) {
$this->files[] = $file;
}
}
public function addFolder($folder)
{
if ($folder instanceof Folder) {
$this->folders[]=$folder;
}
}
}
class File
{
public $filename;
public $filepath;
public function __construct($filename, $filepath)
{
$this->filename = $filename;
$this->filepath = $filepath;
}
}
PHP代码(GetFileSystem.php):
<?php
$config = require_once('config.php');
function getRootContent()
{
$root = array();
$conn = new mysqli($config->host, $config->user, $config->password, $config->db);
if ($conn->connect_error) {
die('Connection failed:' . $conn->connect_error);
}
if ($stmt = $conn->prepare('SELECT id,foldername FROM foldertable WHERE parent_id=? AND published=1')) {
//I only want to get specific folders so there for each id (folderid))
foreach ($config->parentid as $id) {
$root[] = getSubFolders($stmt, $id);
}
} else {
die('Query/Statement Error:' . $conn->error);
}
}
function getSubFolders($stmt, $id)
{
$stmt->reset();
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($folderid, $foldername);
$data = array();
if ($stmt->num_rows > 0) {
while ($stmt->fetch()) {
$data[] = new Folder($folderid, $foldername);
//TO DO $data[] = new File();
}
foreach ($data as $row) {
$row[$folderid] = getSubFolders($stmt, $row['folderid']);
}
}
return $data;
}
$root = new Root(getRootContent());
var_dump($root);
我正在尝试将我的java代码转换为php,因此有些东西可能编码错误(我不是php专家所以任何帮助都会很好)。