2011-11-22 66 views
0

嘗試生成基於父 - >子結構的db驅動菜單。所有根菜單項父列的值是0。Geeting以下錯誤不斷PHP函數問題

Undefined offset: 0,1,2 on line list($id, $parent, $name) = $results; 

Undefined index on line array_key_exists() expects exactly 2 parameters, 1 given on line if (!array_key_exists($tree[$parent]['children'][$id])) { 

Warning: array_key_exists() expects exactly 2 parameters, 1 given on line if (!array_key_exists($tree[$parent]['children'][$id])) { 

PHP代碼

<?php 

function generateMenu($parent, $level, $menu, $utype) { 
    global $db; 
    $tree = array(); 
    $stmt = $db->prepare("select id, parent, name FROM navigation WHERE menu=? AND user_type=?") or die($db->error); 
    $stmt->bind_param("ii", $menu, $utype) or die($stmt->error); 
    $stmt->execute() or die($stmt->error); 
    $stmt->store_result(); 
    $meta = $stmt->result_metadata(); 
    $bindResult = array(); 
    while ($columnName = $meta->fetch_field()) { 
     $bindResult[] = &$results[$columnName->name]; 
    } 
    call_user_func_array(array($stmt, 'bind_result'), $bindResult); 
    while ($stmt->fetch()) { 
     list($id, $parent, $name) = $results; 
     $tree[$id] = array('name' => $name, 'children' => array(), 'parent' => $parent); 
     if (!array_key_exists($id, $tree[$parent]['children'])) { 
      $tree[$parent]['children'][$id] = $id; 
     } 
    } 
    $stmt->close(); 
    print_r($tree); 
} 

?> 

和DB結構

enter image description here

對於測試目的

  • 試過die(print_r($results));while ($stmt->fetch()) {之後。獲取我的數據庫表的第一行爲Array ( [id] => 1 [parent] => 0 [name] => Sual) 1
  • 試過while ($results=$stmt->fetch()) {而不是while ($stmt->fetch()) {。得到了下面的錯誤再次

    上線array_key_exists

    未定義指數()預計2個參數,1線給出的,如果(!array_key_exists($樹[$父] [ '孩子'] [$ ID])){

    警告:array_key_exists()預計2個參數,1線給出的,如果(array_key_exists($樹[$父] [ '孩子'] [$ ID])!){

  • 嘗試if (!array_key_exists($id, $tree[$parent]['children'])) {代替if (!array_key_exists($tree[$parent]['children'][$id])) {。再次出現以下錯誤

    未定義的偏移量:0,1,2在行列表($ id,$ parent,$ name)= $ results;

不知道,怎麼了。請幫助解決該問題

回答

3
 
//try echoing the list values 
//Your syntax is wrong 
array_key_exists($yourKey, $yourSearchArray); 
+0

如果可能,請修改代碼。它會是什麼樣子? –

+0

在list($ id,$ parent,$ name)= $ results之後嘗試了'print_r($ results);'它回顯了所有行'Array([id] => 4 [parent] => 1 [姓名] => Yeni sual)'是的你是對的。但是我必須解決什麼?請修改代碼 –

+0

你在那裏交配? –