Fatal error: Cannot use string offset as an array in C:\xampp\htdocs\includes\categories\categories.php on line 12
$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;时自动完成。
。我们知道它将以空白开始,因为我们在循环之前从一个空数组开始。
关于php - fatal error : Cannot use string offset as an array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12628544/