我如何使用$ _get与build_categories_options函数

时间:2012-09-29 06:12:10

标签: php mysql function get categories

现在我已创建类别并创建帖子成功但是当我编辑我的帖子时我有问题如果编辑我的帖子我会丢失我的类别..我需要在表格中获取我的类别我可以更改它

<?php

$sql = "SELECT catid, catname, parentid FROM categories";
$res = mysql_query($sql);

// initialize $categories to make sure it is an array
$categories = array();
while ($row = mysql_fetch_assoc($res)) {
$parent = intval($row['parentid']);
$categories[$parent][] = $row;
    }
    ?>
    <table border="0" cellpadding="10" cellspacing="0">
    <tr>
    <td valign="top">

    <?php
    $category_string = "";
    function build_categories_options($parent, $categories, $level) {
        global $category_string;
        if (isset($categories[$parent]) && count($categories[$parent])) {
            $level .= " - ";
            foreach ($categories[$parent] as $category) {
                $opt_value = substr($level.$category['catname'],3);
                $category_string .= '<option value=""></option><option value="'.$category['catid'].'">'.$opt_value.'</option>';
                build_categories_options($category['catid'], $categories, $level);
            }
            $level = substr($level, -3);
        }
        return $category_string;
    }
    $category_options = build_categories_options(0, $categories, '');
    $category_options = '<select class="chosen" name="categories" id="categories">'.$category_options.'</select>';
    echo $category_options; 
    ?>
</td>

我的问题位于第25行

$category_string .= '<option value=""></option><option value="'.$category['catid'].'">'.$opt_value.'</option>';

我需要先获取我的类别并显示其余结果。

1 个答案:

答案 0 :(得分:0)

对于每个类别,您将显示两个选项,一个空选项和一个包含类别信息的选项:

$category_string .= '<option value=""></option><option value="'.$category['catid'].'">'.$opt_value.'</option>';

这是在你的循环中。因此,每次循环迭代时,都会创建两个选项。一个空白的,一个与您的类别。我打赌你在<select>的最开头只需要一个空白选项。我想这就是你想要的:

// notice we are initializing $category_string with an empty option here
$category_string = '<option value=""></option>';

function build_categories_options($parent, $categories, $level) {
    global $category_string;
    if (isset($categories[$parent]) && count($categories[$parent])) {
        $level .= " - ";
        foreach ($categories[$parent] as $category) {
            $opt_value = substr($level.$category['catname'],3);

            // removed extra empty category and put it in $category_string initialization
            $category_string .= '<option value="'.$category['catid'].'">'.$opt_value.'</option>';
            build_categories_options($category['catid'], $categories, $level);
        }
        $level = substr($level, -3);
    }
    return $category_string;
}

另外,正如@MoeTsao在评论中提到的那样,尽量避免使用mysql_*函数,因为PHP不鼓励使用它们。相反,请使用mysqli_*PDO