我正在尝试创建一个递归函数(或方法),在数组变量或对象中存储子层导航 . 这是我有的:
class Navigation extends Database
{
function build($parent_id = 0)
{
$query = 'SELECT id, name, href, parent_id
FROM navigation
WHERE parent_id = '.$parent_id.'
ORDER BY name';
$results = $db->query($query);
while ($row = $results->fetch_object()) {
$nav[$row->id] = $row;
// echo $row;
$this->build($row->id);
}
return $nav;
}
}
如果你注释 echo $row 一切正常 . 所以我想要它在三层导航中做的是这样的:
Array
(
[1] => stdClass Object
(
[id] => 1
[name] => Home
[href] => home.php
[parent_id] => 0
)
[2] => stdClass Object
(
[id] => 2
[name] => Company
[href] => company.php
[parent_id] => 0
)
[4] => stdClass Object
(
[id] => 4
[name] => Company Vision
[href] => company_vision.php
[parent_id] => 2
)
[5] => stdClass Object
(
[id] => 5
[name] => Company Goals
[href] => company_goals.php
[parent_id] => 2
)
[3] => stdClass Object
(
[id] => 3
[name] => Products
[href] => products.php
[parent_id] => 0
)
[6] => stdClass Object
(
[id] => 6
[name] => Products Shoes
[href] => products_shoes.php
[parent_id] => 3
)
[7] => stdClass Object
(
[id] => 7
[name] => Nike
[href] => products_shoes_nike.php
[parent_id] => 6
)
)
就像一个例子,所以数组会动态地执行此操作:
$nav[$row->id] = $row; // Home
$nav[$row->id] = $row; // Company
$nav[2][$row->id] = $row; // Company Vision
$nav[2][$row->id] = $row; // Company Goals
$nav[$row->id] = $row; // Products
$nav[3][$row->id] = $row; // Products Shoes
$nav[3][6][$row->id] = $row; // Products Shoes Nike
提前致谢 .
问题:如何创建递归函数/方法并将递归信息存储在变量中而不是回显结果?
问题:(a)PHP每次递归调用时都会覆盖变量(b)解决方案是动态创建一个数组,但我不知道这是否可能