从MySQL数据库创建和显示数组

时间:2017-06-16 08:24:37

标签: php mysqli

我正在尝试修改一些我创建的代码和数据库中的菜单对象数组我需要它将SubCategoryID添加到数组中的每个项目

对于我的生活,我在如何做到这一点上有一种心理上的空白

<?php

include_once ('includes/sqlopen.php');


$sql = mysqli_query($conn, "SELECT CategoryName, SubcategoryName, 
                                   SubcategoryID 
                            FROM products 
                            GROUP BY SubcategoryID 
                            ORDER BY CategoryName");

$menu = array();


while ($row = mysqli_fetch_assoc($sql)) {
    if (!in_array($row['CategoryName'], $menu['category'])) {
        $menu['category'][] = $row['CategoryName'];
    }
    if (!empty($row['SubcategoryName']))
        $menu['SubcategoryName'][$row['CategoryName']][] = $row['SubcategoryName'];
}

echo "Start of Array";
echo "<br>";
foreach ($menu['category'] as $cat) {
    echo $cat."<br>";
    foreach ($menu['SubcategoryName'][$cat] as $subcat) {
        echo "--" . $subcat."<br>";
    }
}
echo "<br>";
echo "End of Array";

include_once ('includes/sqlclose.php');
?>

基本上我想实现这个目标:

Parent Cat 1 (link to prodlist.php?id=100) 
--Child Cat1 (link to prodlist.php?id=103)
--Child Cat2 (link to prodlist.php?id=104)

Parent Cat 2 (link to prodlist.php?id=200)

Parent Cat 3 (link to prodlist.php?id=300)
--Child Cat1 (link to prodlist.php?id=301)
--Child Cat2 (link to prodlist.php?id=302)

并且数据库已经布局:

CategoryName  SubcategoryName ItemName SubCategoryID
ParentCat1,   ChildCat1,      Item1,   103
ParentCat1,   ChildCat1,      Item2,   103
ParentCat1,   ChildCat2,      Item1,   104
ParentCat2,                   Item1,   200
ParentCat3,   ChildCat1,      Item1,   301
ParentCat3,   ChildCat2,      Item2,   302

**更新 - 感谢所有想要帮助我的人,我知道我在解释我需要帮助时可能并不那么出色..

我现在已经玩了一段时间,它正在做我想做的事情。我只是有一个小故障,如果2个不同的父类别具有相同名称的子类别,它会将两个子标签ID添加到数组

$menu = array();


while ($row = mysqli_fetch_assoc($sql)) {

    if (!in_array($row['CategoryName'], $menu['category'])) {
            $menu['category'][] = $row['CategoryName'];
            }
    if (!empty($row['SubcategoryName']))
                $menu['SubcategoryName'][$row['CategoryName']][] = $row['SubcategoryName'];
                $menu['SubcategoryID'][$row['SubcategoryName']][] = $row['SubcategoryID'];

}

输出

--Accessories
id--766
id--243
id--992
id--871
id--977

Monitor Arms
--Spacedec
id--789
--Visidec
id--791
--Telehook
id--792
--Spacepole
id--804
--Accessory
id--866
--Monitor Accessories
id--990
id--584
--Stands
id--991
id--538

3 个答案:

答案 0 :(得分:0)

首先,您可以改善数据库结构

如下所示:

id|category|parent_id

简单而干净不是。

现在试试这个:

//your database records
$rows = [
['id'=>1,'category'=>'Indland','parent_id'=>0],
['id'=>2,'category'=>'Udland','parent_id'=>0],
['id'=>3,'category'=>'Sport','parent_id'=>0],
['id'=>4,'category'=>'Handbold','parent_id'=>3],
['id'=>5,'category'=>'Fodbold','parent_id'=>3],
['id'=>6,'category'=>'Sample','parent_id'=>4]
];

print_r(getList($rows));

// Recursive function
function getList($rows, $id=0){

   // Start a new list
   $newList = null;

   foreach($rows as $key => $row) {
      if ($row['parent_id'] == $id) {
        // Add an UL tag when LI exists
        $newList == null ? $newList = "<ul>" : $newList;
        $newList .= "<li>";
        $newList .= "<a href=\"\">{$row['category']}</a>";
        // Find childrens
        $newList .= getList(array_slice($rows,$key),$row['id']);
        $newList .= "</li>";
    }   
  }   
  // Add an UL end tag
  strlen($newList) > 0 ? $newList .= "</ul>" : $newList;
  return $newList;
}

这将导致:

enter image description here

答案 1 :(得分:0)

DB结构是一个明显的问题,因为它使用的是固定结构。虽然这在某些情况下可能是有效的,但它不容易扩展。实现目前要实现的目标的方法是:

  1. 按CategoryName获取并分组所有项目(在代码中)(我希望类别名称是slug?)
  2. 对于每个类别名称,显示所有具有id
  3. 链接的子类别

    转换为代码,这将是这样的(您当前的SQL查询很好):

    $menu = [];    
    
    while ($row = mysqli_fetch_assoc($sql)) {
        if (!isset($menu[$row['CategoryName']])) {
            $menu[] = $row['CategoryName'];
        }
        if (!empty($row['SubCategoryName']))
            $menu[$row['CategoryName']][] = $row['SubcategoryName'];
        }
    }
    
    echo "Start of Array";
    echo "<br>";
    foreach ($menu as $cat => $catsubs) {
        echo $cat."<br>";
        foreach ($catsubs as $sub) {
            echo "--" . $sub."<br>";
        }
    }
    echo "<br>";
    echo "End of Array";
    

答案 2 :(得分:0)

好吧,伙计们,我想我已经把它推了出来,以便在其他任何人都可以从中获益的情况下再次受益...再次感谢帮助我的每一个人

代码

<?php

include_once ('includes/sqlopen.php');


    $sql = mysqli_query($conn, "SELECT CategoryName, SubcategoryName, CategoryCode, SubcategoryID 
                                    FROM products GROUP BY SubcategoryID ORDER BY CategoryName");

    $menu = array();


    while ($row = mysqli_fetch_assoc($sql)) {
        // Creates First Level Array Items For Parent IDs 
        if (!in_array($row['CategoryName'], $menu['category'])) {
                $menu['category'][] = $row['CategoryName'];
                }
        if (!empty($row['SubcategoryName']))
                    // Creates Second Level Array for Child IDs
                    $menu['SubcategoryName'][$row['CategoryName']][] = $row['SubcategoryName'];
                    // Creates Third Level Array for Category IDs
                    $menu['SubcategoryID'][$row['SubcategoryName']][$row['CategoryName']][] = $row['SubcategoryID'];

    }


echo "Start of Array";
    echo "<br>";

    foreach ($menu['category'] as $cat) {
       echo $cat."<br>";
        foreach ($menu['SubcategoryName'][$cat] as $subcat) {
            echo "--" . $subcat."<br>";
            foreach($menu['SubcategoryID'][$subcat][$cat] as $id)
                echo "id--".$id."<br>";


        } echo "<br>";
    }
    echo "<br>";
    echo "End of Array";



include_once ('includes/sqlclose.php');
?>

<pre>
<?php print_r ($menu); ?>
</pre> 

Foreach循环输出

CPU
--AMD Socket FM2
id--778
--Mobile
id--558
--Intel Socket 1150 (4th Gen)
id--825
--Intel Socket 1151 (6th Gen Skylake)
id--945
--AMD Socket AM3
id--693
--Intel Xeon
id--980
--Intel Socket 2011 (3rd and 4th Gen)
id--744
--Intel Socket 1151 (7th Gen Kabylake)
id--1021
--AMD Socket AM4
id--1023

print_r输出

 [AMD Socket FM2] => Array
                (
                    [CPU] => Array
                        (
                            [0] => 778
                        )

                )

            [Mobile] => Array
                (
                    [CPU] => Array
                        (
                            [0] => 558
                        )

                )

            [Intel Socket 1150 (4th Gen)] => Array
                (
                    [CPU] => Array
                        (
                            [0] => 825
                        )

                )

            [Intel Socket 1151 (6th Gen Skylake)] => Array
                (
                    [CPU] => Array
                        (
                            [0] => 945
                        )

                )

            [AMD Socket AM3] => Array
                (
                    [CPU] => Array
                        (
                            [0] => 693
                        )

                )

            [Intel Xeon] => Array
                (
                    [CPU] => Array
                        (
                            [0] => 980
                        )

                )

            [Intel Socket 2011 (3rd and 4th Gen)] => Array
                (
                    [CPU] => Array
                        (
                            [0] => 744
                        )

                )