所以我正在创建这个cms,
它使用主页和子页面(达到无限级别)
通常我做过(请记住,这是一个例子):
function getPages($parent_id = 0)
{
$data = mysql("select * from pages WHERE parent_id=$parent_id");
if($data)
{
for($i=0; $i < count($data); $i++)
{
$data[$i]['subpages'] = getPages($data[$i]['id'];
}
}
return $data;
}
现在我想在一个查询中执行类似的操作,我将从页面中选择所有子页面到无限级别,我希望它作为子数组返回,而不是覆盖主数据(因为列名称)
表名与主页及其自己的子页面相同(页面)。
结构:
`id` int(11) NOT NULL,
`parent_id` int(11) NOT NULL,
`language_id` int(11) NOT NULL,
`location_id` int(11) NOT NULL,
`order` int(11) NOT NULL,
`active` tinyint(1) NOT NULL,
`follow` tinyint(1) NOT NULL,
`title` varchar(255) NOT NULL,
`sub_title` varchar(255) NOT NULL,
`page_title` varchar(255) NOT NULL,
`url` varchar(255) NOT NULL,
`content` text NOT NULL,
`seo_tags` varchar(255) NOT NULL,
答案 0 :(得分:1)
<?
// Filling $data for the example. You can replace following lines by
// $data = mysql("select * from pages");
$data = array(
array("id" => 1, "name" => "a", "parent_id" => 0 ),
array("id" => 2, "name" => "b", "parent_id" => 1 ),
array("id" => 3, "name" => "c", "parent_id" => 2 ),
array("id" => 4, "name" => "d1", "parent_id" => 3 ),
array("id" => 5, "name" => "d2", "parent_id" => 3 )
);
function getPages($parent_id = 0)
{
global $data;
$result = array();
$resultSize = 0;
if($data)
{
$countData = count($data);
for($i=0; $i < $countData; $i++)
{
if ($data[$i]["parent_id"] == $parent_id) {
$result[$resultSize] = $data[$i];
$subpage = getPages($data[$i]["id"]);
if (!empty($subpage)) {
$result[$resultSize]["subpages"] = $subpage;
}
$resultSize++;
}
}
}
return $result;
}
print_r(getPages(0));
?>