有没有更好的方法在 PHP 中使用循环对查询结果进行分组?

发布于 2024-09-17 06:23:07 字数 1706 浏览 3 评论 0原文

这是我在 stackoverflow 中提出的第一个问题。

我有两个 MYSQL 表:类别和产品。我使用 PHP 中的 while 循环来管理查询结果,将每个类别及其产品分组。这是我第一次这样做,我认为我做得非常“狡猾/硬编码”(对不起我的英语)。我认为这应该是更好的方法。所以想请教一下专业程序员。这是我的代码:

 CREATE TABLE IF NOT EXISTS `categories` (
 `id` int(11) NOT NULL auto_increment,
 `name` text NOT NULL,
 PRIMARY KEY  (`id`)
 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;


 CREATE TABLE IF NOT EXISTS `products` (
 `id` int(11) NOT NULL auto_increment,
 `name` text NOT NULL,
 `description` text NOT NULL,
 `category` int(11) NOT NULL,
 `photo` int(11) NOT NULL,
  PRIMARY KEY  (`id`)
 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=33 ;

我有一个返回与其类别相关的产品的查询:

SELECT categories.name as category,products.name as product
FROM categories
INNER JOIN products ON(categories.id = products.category)

使用 PHP,我管理结果,为每个类别及其产品创建一个无序列表:

<?php
$category = '';//A control variable

while($row = mysql_fetch_array($query))
{
    //if its a new category I start a new <ul>
    if($row['category'] != $category)
    {
        //If it´s not the firt category I need to close previous one
        if($category != '')
        {
            echo "</ul>\n";
        }
        //I start the new <ul>
        echo '<h2>' . $row['category'] . '</h2>';
        echo '<ul>';
    }

    //I create the correspondient <li>
    echo '<li>' . $row['product'] . "</li>\n";

    //Asign the value of actual category for the next time in the loop
    $category = $row['category'];

}

//I neeed to close last <ul>
echo "</ul>\n";
?>

是否有更好的方法来执行此操作? 预先感谢您的回答!

that´s my first question in stackoverflow.

I have two MYSQL tables: categories and products. I manage the query results with a while loop in PHP to group every category with its products. It´s the first time I do something so, and I think I made it very "crafty/hardcoded" (Sorry for my English). I think that should be a better way to do this. So, I´d like to ask to professional programmers. Here is my code:

 CREATE TABLE IF NOT EXISTS `categories` (
 `id` int(11) NOT NULL auto_increment,
 `name` text NOT NULL,
 PRIMARY KEY  (`id`)
 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;


 CREATE TABLE IF NOT EXISTS `products` (
 `id` int(11) NOT NULL auto_increment,
 `name` text NOT NULL,
 `description` text NOT NULL,
 `category` int(11) NOT NULL,
 `photo` int(11) NOT NULL,
  PRIMARY KEY  (`id`)
 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=33 ;

I have a query that returns products relationed with their category:

SELECT categories.name as category,products.name as product
FROM categories
INNER JOIN products ON(categories.id = products.category)

With PHP I manage the results to create an unordered list for every category with its products:

<?php
$category = '';//A control variable

while($row = mysql_fetch_array($query))
{
    //if its a new category I start a new <ul>
    if($row['category'] != $category)
    {
        //If it´s not the firt category I need to close previous one
        if($category != '')
        {
            echo "</ul>\n";
        }
        //I start the new <ul>
        echo '<h2>' . $row['category'] . '</h2>';
        echo '<ul>';
    }

    //I create the correspondient <li>
    echo '<li>' . $row['product'] . "</li>\n";

    //Asign the value of actual category for the next time in the loop
    $category = $row['category'];

}

//I neeed to close last <ul>
echo "</ul>\n";
?>

Is there a better way to do this operation?
Thanks in advance for your answers!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

世界和平 2024-09-24 06:23:07

最好不要将 HTML 与 PHP 混合在一起。

既然您需要我的建议(大约 12 年的资深 PHP 编码员),我将快速从头开始编码:

<?php
$pdo = new PDO($dsn, $user, $pass);

$sql = "SELECT categories.name as category,products.name as product
FROM categories
INNER JOIN products ON(categories.id = products.category)";

$stmt = $pdo->prepare($sql);
$stmt->execute();

$categories = array();
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)))
{
    $category = $row['category'];
    $categories[$category][] = $row['product'];
}

// In your view:
?>
<html>
    <body>
<?php
    foreach ($categories as $category => $products)
    {
?>
        <h2><?php echo $category; ?></h2>
        <ul class="products">
<?php
        foreach ($products as $product)
        {
?>
            <li><?php echo $product; ?></li>
<?php
        }
?>
        </ul>
<?php
    }
?>
    </body>
</html>

It's always best not to mix HTML with PHP.

Since you wanted my advice (veteran PHP coder of some 12 years), I'll just code it from scratch real fast:

<?php
$pdo = new PDO($dsn, $user, $pass);

$sql = "SELECT categories.name as category,products.name as product
FROM categories
INNER JOIN products ON(categories.id = products.category)";

$stmt = $pdo->prepare($sql);
$stmt->execute();

$categories = array();
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)))
{
    $category = $row['category'];
    $categories[$category][] = $row['product'];
}

// In your view:
?>
<html>
    <body>
<?php
    foreach ($categories as $category => $products)
    {
?>
        <h2><?php echo $category; ?></h2>
        <ul class="products">
<?php
        foreach ($products as $product)
        {
?>
            <li><?php echo $product; ?></li>
<?php
        }
?>
        </ul>
<?php
    }
?>
    </body>
</html>
听风念你 2024-09-24 06:23:07

我建议阅读分层数据。很棒的一本书。您应该特别注意嵌套集模型。

它确实需要一些时间来学习,也需要一些时间来实施,但为了最终的结果是非常值得的!

I would suggest reading into Hierarchical Data. A great read. You should particularly pay attention to the Nested Set Model.

It does take a bit to learn and also takes a bit to implement, but is well worth it for the end result!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文