2012-09-27 150 views
0

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> 

之後我插入後採用按類別將顯示此錯誤?

+0

你能指出12行請問 – Flosculus

+0

'$ categories'是什麼?我敢打賭這是一個字符串...或$ $ [$ parent]是一個字符串。 – Travesty3

+0

即時通訊思考相同。 http://stackoverflow.com/questions/2058635/cannot-use-string-offset-as-an-array-error – Flosculus

回答

0

我沒有看到$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][] = $row;你並不需要顯式初始化$categories[$parent] ......這將是自動完成的。我們知道它會從空白開始,因爲我們在循環之前使用了一個空數組。

相關問題