将它们全部存储在数组中有什么问题?除非您计划在这些菜单项中包含数千个元素(这对用户来说非常不友好),否则对于 PHP 来说这只是在公园里散步。
此外,您可能希望更具体地了解您的要求。是 jQuery、PHP 还是两者兼而有之?你需要代码还是概念?
编辑:解决方案
因此,根据您列出的评论,这是一个概念证明。
PHP:您需要从数据库中读取并将它们加载到数组中。使用 PDO 很容易做到这一点。只需使用该fetchAll()
命令并在关联数组中检索整个结果集。棘手的部分是将您的“平面”数据库转换为多维数组。开始:
// Retrieve the details from the database in the $rows associative array
...
// Now, we need to expand the 'flat' DB structure into a multi-
// dimensional array.
$multid=findKids($rows);
// Send it back, JSON-encoded
die(json_encode(
'result' => 'success',
'response' => $multid
)); // Send the response back via AJAX
/**
* Here's the function that converts the flat DB into a multi-
* dimensional array. It tracks all the parents in a single
* array and collects the kids for those parents. If it comes
* across a new parent, if fetches all the kids recursively.
*/
function findKids( $rows, $parentid=NULL, &$parents=NULL ) {
// Create a temporary array for the kids
$shelter;
// Go through all the rows
foreach($rows as $index => $row) {
// Find the kids that belong to this parent
if($row['parentid']==$parentid) {
// This kid belongs to this parent
// Move it to the temporary shelter
$shelter[$parentid][]=$row;
}
else {
// This kid doesn't belong to this parent.
// Have we already talked to the parent before?
if(isset($parents[$row['parentid']])) {
// Yes, the parent has already been visited. Ignore
}
else {
// Parent hasn't been visited; add it
$shelter[$row['parentid']][]=findKids($rows,$row['parentid'],$parents);
}
} // close else{ }
} // close foreach{ }
// Return the shelter, with all the kids
return $shelter;
}
返回的数组将包含如下所示的响应:
$response=[
'result'=>'success',
'response'=>[
0=>[ // Contains the kids for $parentid=0
['id'=>1, 'cat_id'=>1, 'parent_id'=>0],
['id'=>2, 'cat_id'=>1, 'parent_id'=>0]
],
1=>[ // Contains the kids for $parentid=1
['id'=>3, 'cat_id'=>1, 'parent_id'=>1],
['id'=>4, 'cat_id'=>1, 'parent_id'=>1],
['id'=>5, 'cat_id'=>1, 'parent_id'=>1]
],
]
];
jQuery:您将解释 JSON 响应并遍历响应以动态创建菜单。
这是一个将数组显示为嵌套无序列表的示例脚本。
// Call the printMyFamily method on the element to display
// that you'd like to see the menu appear in
$outputElem.html($.printMyFamily(NULL,response['response']));
$.printMyFamily = function(parentid,haystack){
// Our output variable
output="<ul>";
// Find the kids
$haystack.each(function(index,elem){
// Is this kid ours?
if(elem[parentid] == parentid){
// Yes. Add to output
output+="<li id='"+elem['id']+"'>"+elem['catid']+"</li>";
// Find this items kids (if any)
output+=$.printMyFamily(elem['id'],haystack);
}
else { /* not ours, ignore */ }
});
// Is the result an empty string? If so, just clear it
if(output=="<ul>"){ output=""; }
// Return the output
return output;
};