使用php将moodle数据库数据显示为ul li

时间:2013-01-13 14:31:26

标签: php mysql database moodle

  

可能重复:
  Nested array. Third level is disappearing

我有点问题,使用php显示moodle数据库数据为ul li form。 我想以正确的嵌套形式显示所有类别的课程,而不是课程,如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>";
        }
    }   
}
?>

我很难理解出了什么问题?

1 个答案:

答案 0 :(得分:0)

我认为这对你有帮助 -

$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);
}

由于