簡體   English   中英

致命錯誤:無法將字符串偏移量用作數組

[英]Fatal error: Cannot use string offset as an array

致命錯誤:無法在第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>

在我插入帶有類別的帖子后,將顯示此錯誤?

我看不到$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;時自動完成$categories[$parent][] = $row; 我們知道它將開始為空,因為我們在循環之前從一個空數組開始。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM