0

致命错误:不能在第 12 行的 C:\xampp\htdocs\includes\categories\categories.php 中使用字符串偏移作为数组

$categories[$parent][] = $row;

类别.php

    <?php

$sql = "SELECT catid, catname, parentid FROM categories";
$res = mysql_query($sql);
while ($row = mysql_fetch_assoc($res)) {
    $parent = intval($row['parentid']);
    if (!isset($categories[$parent])) {
        $categories[$parent] = array();
    }
    $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>

在我插入带有类别的帖子后,此错误将显示?

4

1 回答 1

3

我看不到在哪里$categories初始化,但我敢打赌当你进入while循环时它不是一个数组,这就是你收到错误的原因。尝试为您的while循环执行此操作:

// initialize $categories to make sure it is an array
$categories = array();
while ($row = mysql_fetch_assoc($res)) {
    $parent = intval($row['parentid']);
    $categories[$parent][] = $row;
}

您不需要显式初始化$categories[$parent]...这将在您调用时自动完成$categories[$parent][] = $row;。我们知道它会从空白开始,因为我们在循环之前从一个空数组开始。

于 2012-09-27T19:24:19.417 回答