0

可能重复:
嵌套数组。第三层正在消失

我在使用 php 将 moodle 数据库数据显示为 ul li 表单时遇到了问题。我想以适当的嵌套形式显示所有课程类别,而不是课程,如 ul li。我正在处理的表是 mdl_course_categories。每当 php 脚本运行时,列表必须动态更新代码如下所示:

<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}

mysql_select_db("moodle19", $con);
$result = mysql_query("SELECT name AS COURSE_NAME,parent FROM mdl_course_categories");

if (isset($result)!=1) {
$message  = 'Invalid query: ' . mysql_error() . "\n";
}
echo "<p> The courses taught are: </p>";

while ($row = mysql_fetch_array($result)) {
$b=$row['COURSE_NAME'];
$c=$row['parent'];

//      $a=mysql_query("Select id from mdl_course_categories");
//      $condition=mysql_query("SELECT name AS COURSE_NAME FROM mdl_course_categories WHERE parent='0'");

    if ($c==0) {
    echo "<ul>
    <li>" .$b. "</li>
    </ul>";
    }

    else {
        echo "<ul>
            <li>" .$b. "</li>
            </ul>";
    $result1 = mysql_query("SELECT name AS COURSE_NAME FROM mdl_course_categories WHERE depth!='1'");
    while ($row1 = mysql_fetch_array($result1)) {

        $b1=$row1['COURSE_NAME'];
        echo "<ul>
            <li>" .$b1. "</li>
            </ul>";
        }
    }   
}
?>

我对出了什么问题感到困惑?

4

1 回答 1

0

I think this will helpful for you -

$query_catetories = mysql_query('SELECT cc.id, cc.parent, cc.name FROM mdl_course_categories cc ');
$categories = mysql_fetch_all($query_catetories);

$tmp_categories = array();

foreach ($categories AS $row) {

    $row['id'] = (int) $row['id'];
    $row['parent'] = (int) $row['parent'];
    if (!$tmp_categories[$row['parent']])
        $tmp_categories[$row['parent']] = array();
    $tmp_categories[$row['parent']][] = $row;
}

$course_catetories = buildNode($tmp_categories);

echo '<ul>';
foreach ($course_catetories as $course_catetory) {
    print_category_child($course_catetory);
}
echo '</ul>';

function print_category_child($category) {
    echo '<li>' . $category['name'];
    if (array_key_exists('children', $category)) {
        echo '<ul>';
        foreach ($category['children'] as $child) {
            print_category_child($child);
        }
        echo '</ul>';
    }
    echo '</li>';
}

function buildNode($inputArray, $parent = 0) {
    $return = array();
    foreach ($inputArray[$parent] AS $key => $row) {
        if (@$inputArray[$row['id']]) {
            $row['children'] = buildNode($inputArray, $row['id']);
        }
        $return[] = $row;
    }
    return $return;
}

function mysql_fetch_all($result) {
    $all = array();
    while ($all[] = mysql_fetch_assoc($result)) {

    }
    return array_filter($all);
}

Thanks

于 2013-01-14T11:12:53.403 回答