如何在 PHP 中从数组创建嵌套列表(菜鸟)
我有一个应用程序,用户可以选择项目,然后填充一个包含两列的表格:类别和项目。它是这样的:
Category | Items
-----------------
PET | Dog Food
HEALTH | Tooth Brush
PET | Cat Food
COLD FOOD | Steak
COLD FOOD | Eggs
在我的 select 语句中,我按类别对数据进行排序,然后按项目排序,并且我使用 WHILE 循环将数据放入数组中。
while($listItems = mysql_fetch_array($results))
{
$myArray[] = array("category" => $listItems["Category"],
"item" => $listItems["Name"]);
}
当我执行 print_r($myArray); 时我得到这样的结果:
Array ( [0] => Array ( [category] => Cold Food [item] => Steak )
[1] => Array ( [category] => Food [item] => Eggs )
[2] => Array ( [category] => Health [item] => Tooth Brush )
[3] => Array ( [category] => Pet [item] => Cat Food )
[4] => Array ( [category] => Pet [item] => Dog Food ) )
我想要做的是将数据输出到类似这样的嵌套列表中。
- 冷食
- 牛排
- 鸡蛋
- 保健
- 牙刷
- 宠物
- 猫粮
- 狗粮
欢迎任何帮助!谢谢!
I have an app that users choose items and then it fills a table that has two columns in it: Category and Items. Its something like this:
Category | Items
-----------------
PET | Dog Food
HEALTH | Tooth Brush
PET | Cat Food
COLD FOOD | Steak
COLD FOOD | Eggs
In my select statement I order the data by Category then by Items and I am using a WHILE loop to drop the data into an array.
while($listItems = mysql_fetch_array($results))
{
$myArray[] = array("category" => $listItems["Category"],
"item" => $listItems["Name"]);
}
When I do a print_r($myArray); I get something like this:
Array ( [0] => Array ( [category] => Cold Food [item] => Steak )
[1] => Array ( [category] => Food [item] => Eggs )
[2] => Array ( [category] => Health [item] => Tooth Brush )
[3] => Array ( [category] => Pet [item] => Cat Food )
[4] => Array ( [category] => Pet [item] => Dog Food ) )
What I am wanting to do is output the data into a nested list something like this.
- Cold Food
- Steak
- Eggs
- Health
- Tooth Brush
- Pet
- Cat Food
- Dog Food
Any help is welcomed! Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
试试这个:
然后,要输出它,你可以这样做:
Try this:
Then, to output it you'd do this:
尝试一下。其想法是将数据重新组织为更方便的形式,即按类别对项目建立索引。
代码
输出
Give this a try. The idea is to reorganize your data into a more convenient form, namely to have the items indexed by category.
Code
Output
尝试用这个:
Try with this: