我有一个用户选择项目的应用程序,然后它填充一个包含两列的表:类别和项目。它是这样的:
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 ) )
我想要做的是将数据输出到这样的嵌套列表中。
欢迎任何帮助!谢谢!
答案 0 :(得分:4)
试试这个:
while($listItems = mysql_fetch_array($results))
{
$cat = $listItems['Category'];
$name = $listItems['Name'];
if(!isset($myArray[$cat]))
$myArray[$cat] = array();
$myArray[$cat][] = $name;
}
然后,输出它你会这样做:
$buffer = '<ul>';
foreach($myArray as $cat => $items) {
$buffer .= "<li>$cat</li><li><ul>";
foreach($items as $item) {
$buffer .= "<li>$item</li>";
}
$buffer .= '</ul></li>';
}
$buffer .= '</ul>';
echo $buffer;
答案 1 :(得分:1)
试一试。我们的想法是将您的数据重组为更方便的形式,即按类别索引项目。
<?php
$items = array
(
array('category' => 'Cold Food', 'item' => 'Steak'),
array('category' => 'Food', 'item' => 'Eggs'),
array('category' => 'Health', 'item' => 'Tooth Brush'),
array('category' => 'Pet', 'item' => 'Cat Food'),
array('category' => 'Pet', 'item' => 'Dog Food'),
);
// Group the items by category.
$itemsByCategory = array();
foreach ($items as $item)
{
$category = $item['category'];
$name = $item['item'];
if (!array_key_exists($category, $itemsByCategory))
$itemsByCategory[$category] = array();
$itemsByCategory[$category][] = $name;
}
// Output nested lists for the items.
?> <ul>
<?php foreach ($itemsByCategory as $category => $items)
{
?> <li><?php echo htmlspecialchars($category); ?>
<ul>
<?php foreach ($items as $item)
{
?> <li><?php echo htmlspecialchars($item); ?></li>
<?php }
?> </ul>
</li>
<?php }
?> </ul>
- 冷食
- 牛排
- 食品
- 蛋
- 健康
- 牙刷
- 宠物
- 猫粮
- 狗粮
答案 2 :(得分:1)
<?
//establish $vlink before
$query = 'select distinct (category) from list';
$result = mysql_query($query,$vlink);
while($row = mysql_fetch_array($results))
{
$query1 = "select items from list where category = ".$row[0];
$result1 = mysql_query($query1,$vlink);
echo '<h1>'.$row[0].'</h1>';
while($row1 = mysql_fetch_array($result1))
{
echo '<h2>'.$row1[0].'</h2>';
}
}
?>
答案 3 :(得分:0)
试试这个:
while($listItems = mysql_fetch_array($results))
{
$myArray[$listItems["Category"]][] = $listItems["Name"]
}