致命错误:不能将字符串偏移用作数组

时间:2012-09-27 19:15:30

标签: php mysql arrays offset

  

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

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

categories.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>

我插入帖子后有类别此错误会显示?

1 个答案:

答案 0 :(得分:1)

我没有看到$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;时自动完成。我们知道它会以空白开始,因为我们在循环之前开始使用空数组。