我想做的是生成导航菜单,例如
<ul>
<li>
<ul>
...........
</ul>
</li>
</ul>
来自数据库,只有一个查询。但是一旦我执行以下函数,它就不会停止。 (似乎有逻辑错误)。请看一下,有什么问题
<?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();
// the following creates a bind_result string with an argument for each column in the query
// e.g. $stmt->bind_result($results["id"], $results["foo"], $results["bar"]);
$bindResult = '$stmt->bind_result(';
while ($columnName = $meta->fetch_field()) {
$bindResult .= '$results["' . $columnName->name . '"],';
}
$bindResult = rtrim($bindResult, ',') . ');';
// executes the bind_result string
eval($bindResult);
$stmt->fetch();
$stmt->close();
while (list($id, $parent, $name) = $results) {
$tree[$id] = array('name' => $name, 'children' => array(), 'parent' => $parent);
if (!array_key_exists($tree[$parent]['children'][$id])) {
$tree[$parent]['children'][$id] = $id;
}
}
print_r($tree);
}
?>
最佳答案
不确定这是否是问题所在,但我建议使用 call_user_func_array
而不是 eval
来调用 bind_result
。
$bindResult = array();
while ($columnName = $meta->fetch_field()) {
// Needs to passed by reference, so that it creates the $results array correctly
$bindResult[] = &$results[$columnName->name];
}
call_user_func_array(array($stmt, 'bind_result'), $bindResult);
编辑:您的问题是需要为每一行调用 $sql->fetch()
,而不仅仅是一次。代码会永远循环,因为您不断读取同一行。试试这个:
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();
$results = array();
while ($columnName = $meta->fetch_field()) {
// Needs to passed by reference, so that it creates the $results array correctly
$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($tree[$parent]['children'][$id])) {
$tree[$parent]['children'][$id] = $id;
}
}
$stmt->close();
print_r($tree);
}
关于php - PHP函数中的逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8219313/