简体   繁体   English

使用 PHP 从 MySQL DB 中订购项目列表中的标题

[英]Order headings in list of items from MySQL DB with PHP

Hoping someone has an idea of a good way to query/handle these headings...希望有人有一个查询/处理这些标题的好方法的想法......

As an example, if you have a recipe, it might look like this: (with headings and ingredients)例如,如果您有一个食谱,它可能如下所示:(带有标题和成分)


Salad 沙拉

  • Fresh Lettuce新鲜生菜
  • Chopped carrots切碎的胡萝卜
  • Fresh Strawberries新鲜草莓

Dressing敷料

  • Vinegar
  • Sugar
  • Cinnamon肉桂

Garnish装饰

  • Sliced Almonds杏仁片

In the MySQL database, I'll be storing this data in a recipe table.在 MySQL 数据库中,我将把这些数据存储在一个配方表中。 So this recipe might look like this:所以这个食谱可能是这样的:

 +----+---------------+-----------------+--------------------+---------------------+-----------+---------+-----------+---------+-----------+---------+ | id | ingredient_1 | ingredient_2 | ingredient_3 | ingredient_4 etc... | heading_a | h_a_pos | heading_b | h_b_pos | heading_c | h_c_pos | +----+---------------+-----------------+--------------------+---------------------+-----------+---------+-----------+---------+-----------+---------+ | 1 | Fresh Lettuce | Chopped carrots | Fresh Strawberries | Vinegar | Salad | 1 | Dressing | 4 | Garnish | 7 | +----+---------------+-----------------+--------------------+---------------------+-----------+---------+-----------+---------+-----------+---------+

Where the ingredients are all stored together, and the headings are stored together.成分全部存储在一起,标题存储在一起的地方。 (Different recipes will need different headings and in different positions in relation to ingredients.) Here the heading position (h_a_pos, etc.) indicate the ingredient # to list the heading before. (不同的食谱将需要不同的标题,并且相对于成分处于不同的位置。)这里的标题位置(h_a_pos 等)指示成分# 以在前面列出标题。

When it comes to querying this to display it, if I run a simple SQL query:当涉及到查询以显示它时,如果我运行一个简单的 SQL 查询:

 SELECT * FROM recipes WHERE id = 1;

That will just return me a list of everything.那只会返回给我所有内容的列表。 Here's an SQL Fiddle: http://sqlfiddle.com/#!9/942d8a3/1/0这是一个 SQL 小提琴: http ://sqlfiddle.com/#!9/942d8a3/1/0

With PHP, I could then take the results, and put it into an array.使用 PHP,我可以获取结果,并将其放入一个数组中。 And I'm sure there's some way I could sort them, but I'm drawing a blank...而且我确定我可以通过某种方式对它们进行排序,但是我正在画一个空白...

 $response = []; // blank array $sql_retrieve = $con->prepare("SELECT * FROM recipes WHERE id = 1"); $sql_retrieve->execute(); $result = $sql_retrieve->get_result(); if($result->num_rows>0){ while($row=$result->fetch_assoc()){ $response[] = $row; } // end of while } // end of num_rows print_r($response); // display response pre-sorting // sort array -- not working usort($response, function($a, $b) { return $a['h_a_pos'] <=> $b['h_b_pos']; }); // would need something to order it in relation to the ingredients... echo '<br /><br />'; print_r($response); // display response post-sorting

I can change the database structure, but would prefer to keep this within one table if at all possible.我可以更改数据库结构,但如果可能的话,我更愿意将其保留在一张表中。 (I realize some of the ingredients may not be normalized, but I'm not listing the amounts, etc. in this example either.) (我意识到某些成分可能未标准化,但我也没有在此示例中列出数量等。)

Anyone have any ideas on how to store the headings?有人对如何存储标题有任何想法吗? I basically just need to know that it's supposed to be a heading (so it can be formatted appropriately), what the text should be, and before which ingredient number to display it.我基本上只需要知道它应该是一个标题(所以它可以被适当地格式化),文本应该是什么,以及在哪个成分编号之前显示它。 (I'd never be querying off the headings, so if this would be better stored serialized, that might be an option...) (我永远不会查询标题,所以如果这可以更好地序列化存储,那可能是一个选择......)

What you've got there is not normal .你得到的东西不正常 You will run into troubles if, for example, you decide you want a complex recipe with more ingredients than columns, or more ingredient headings than columns.例如,如果您决定需要一个复杂的食谱,其中的成分比列多,或者成分标题比列多,您就会遇到麻烦。 The important lesson to take away is that databases are not spreadsheets.要吸取的重要教训是数据库不是电子表格。

Here's something closer to the database structure that you want:这是更接近您想要的数据库结构的内容:

CREATE TABLE categories (id SERIAL, name VARCHAR(32));
CREATE TABLE ingredients (id SERIAL, category_id BIGINT UNSIGNED NOT NULL, name VARCHAR(32));
CREATE TABLE recipes (id SERIAL, name VARCHAR(32));
CREATE TABLE ingredients_recipes (recipe_id BIGINT UNSIGNED NOT NULL, ingredient_id BIGINT UNSIGNED NOT NULL);

Obviously, you'd want some foreign key constraints in there as well to enforce links between tables, but we'll skip that here.显然,您还需要一些外键约束来强制表之间的链接,但我们将在此处跳过。 Populate it with your ingredients:用你的配料填充它:

INSERT INTO categories VALUES (1, 'Salad'), (2, 'Dressing'), (3, 'Garnish');
INSERT INTO ingredients VALUES (1, 1, 'Fresh Lettuce'), (2, 1, 'Chopped Carrots'), (3, 1, 'Strawberries'), (4, 2, 'Balsamic Vinegar'), (5, 2, 'Olive Oil'), (6, 3, 'Sliced Almonds');
INSERT INTO recipes VALUES (1, 'My Salad');
INSERT INTO ingredients_recipes VALUES (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6);

Now, the full recipe can be pulled using simple joins:现在,可以使用简单的连接来提取完整​​的配方:

SELECT r.name AS recipe, c.name AS category, i.name AS ingredient
FROM ingredients i
LEFT JOIN categories c ON (i.category_id = c.id)
LEFT JOIN ingredients_recipes ON (ingredient_id = i.id)
LEFT JOIN recipes r ON (recipe_id = r.id)
WHERE r.id = ?
ORDER BY c.id ASC

Here's a fiddle to illustrate this: http://sqlfiddle.com/#!9/aecbbd/1这里有一个小提琴来说明这一点: http : //sqlfiddle.com/#!9/aecbbd/1

(Note the order of the "headings" is going to have to be something defined separately, at the time they're created. In this case I've just sorted by ID.) (请注意,“标题”的顺序必须在创建它们时单独定义。在这种情况下,我只是按 ID 排序。)

Now, in your PHP you can easily execute this query and group the ingredients by category:现在,在您的 PHP 中,您可以轻松执行此查询并按类别对成分进行分组:

$stmt = $con->prepare($query);
$stmt->bind_param("i", $recipe_id);
$stmt->execute();
while ($row = $stmt->fetch_assoc()) {
    $name = $row["recipe"];
    $ingredient_types[$row["category"]][] = $row["ingredient"];
}

And during display, simply loop through the arrays:在显示期间,只需循环遍历数组:

<h1>How to make <?= $name ?></h1>
<?php foreach($ingredient_types as $category=>$ingredients): ?>
    <h2><?= $category ?></h2>
    <ul>
    <?php foreach ($ingredients as $ingredient): ?>
        <li><?= $ingredient ?></li>
    <?php endforeach ?>
    </ul>
<?php endforeach ?>

Your question mentioned quantities, these would be stored in the pivot table ingredients_recipes as an additional column and could easily be pulled into the SELECT clause.您的问题提到了数量,这些将作为附加列存储在数据透视表ingredients_recipes ,并且很容易被拉入SELECT子句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM