[英]Inserting mysql database results into a multidimensional array in php
Hi Im trying to build a dynamic navigation menu similar on how wordpress does it or so I think but my problem is that my script retrieves only 1 value from my database. 您好,我试图建立一个动态导航菜单,类似于wordpress的工作方式,所以我认为我的问题是我的脚本仅从数据库中检索1个值。 What I was trying to accomplish here is to fetch all menu data in my database and store them in a multidimensional array
我在这里试图完成的工作是获取数据库中的所有菜单数据并将它们存储在多维数组中
My database structure looks like this: 我的数据库结构如下所示:
Here is how I retrieve the data 这是我如何检索数据
global $db;
$sql = "SELECT * FROM lm_menu";
$res = $db->prepare($sql);
$res->execute();
$result = $res->fetchAll();
foreach ($result as $opt_h):
$nav = array(
array(
'id' => $opt_h['id'],
'name' => $opt_h['name'],
'link' => $opt_h['ref'],
'parent' => $opt_h['parent']
)
);
endforeach;
And this is the function that reads the array 这是读取数组的函数
function GenerateMenu($nav)
{
$html = '';
$html = '<ul class="nav navbar-nav">';
foreach($nav as $page)
{
$html .= '<li>';
$html .= '<a href="' . $page['link'] . '">' . $page['name'] . '</a>';
$html .= GenerateNavHTML($page['sub']);
$html .= '</li>';
}
$html .='</ul>';
return $html;
}
I tried looking for an answer from google but found no luck I saw an article from SO but I didn't tried it because on that article it uses a mysql_* functions while I use PDO functions. 我尝试从Google寻找答案,但没有发现我看到SO的文章 ,但是我没有尝试过,因为在那篇文章中它使用了mysql_ *函数,而我使用了PDO函数。 Please Help me guys on this one
请帮助我这个家伙
The problem is every iteration, $nav = array(
is overwritten. 问题是每次迭代,
$nav = array(
被覆盖。
Might as well just return $nav = $res->fetchAll(PDO::FETCH_ASSOC);
还可以返回
$nav = $res->fetchAll(PDO::FETCH_ASSOC);
. 。 No need to loop and reassign.
无需循环和重新分配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.