PHP数组问题'非法字符串偏移'

时间:2015-11-26 22:02:06

标签: php arrays

我正在尝试从MySQL数据库创建一个导航菜单。我有这个代码,它接受一个mysql查询($ row)的结果数组并将它们放入($ item)。当我处理每个$项目时,我收到了这些警告:

  

警告:非法字符串偏移' parent_id'在第52行的C:\ xampp \ htdocs \ bootstrap \ includes \ navigation.php中   警告:非法字符串偏移' parent_id'在第52行的C:\ xampp \ htdocs \ bootstrap \ includes \ navigation.php中   警告:非法字符串偏移'页面'在第53行的C:\ xampp \ htdocs \ bootstrap \ includes \ navigation.php

我尝试将$item['id']$item['page']$item['parent_id']分别更改为$item[0]$item[1]$item[2],但这并没有工作要么。我已经漫游谷歌试图看看还能做些什么。此代码借鉴了在此处运行的解决方案:

http://www.websitesdevelopments.com/blog/post/dynamic-multilevel-css-drop-down-menu-using-css-php-and-mysql

但我不知道为什么它不适合我。

<?php
include("includes/database.php");

try {
    // read all pages from the database     
    $query = "SELECT * FROM pages";     

    // prepare query statement
    $stmt = $con->prepare( $query );

    // execute query
    $stmt->execute();

    //count the number of pages
    $num = $stmt->rowCount();

    //put results array into variable
    $rows = $stmt->fetch(PDO::FETCH_ASSOC);

}catch(PDOException $e) { 
    //something wrong with query/datbase connection
    echo $e->getMessage();
}

?>

 <?php
     $items = $rows;
     $id = '';
     print_r($items);

    foreach($items as $item){
      if($item['parent_id'] == 0){
          echo "<li><a href='#'>".$item['page']."</a>";
          $id = $item['id'];
          sub($items, $id);
          echo "</li>";
      }
    }
     echo "</ul>";

    function sub($items, $id){
        echo "<li class='dropdown'>";
        echo "<a href='#' class='dropdown-toggle' data-toggle='dropdown'>Portfolio <b class='caret'></b></a>";
        echo "<ul class='dropdown-menu'>";
        foreach($items as $item){
            if($item['parent_id'] == $id){
                echo "<li><a href='?page=".$item['page']."'>".$item['page']."</a>";
                sub($items, $item['id']);
                echo "</li>";
            }
        }
        echo "</ul>";
    }

     ?>

0 个答案:

没有答案