如何在一个表行中显示多个记录

时间:2016-10-19 08:34:09

标签: php mysql loops

如何在一个表格行中显示多条记录? 我使用单词解释不好,所以我将使用一个例子:

Work No. | Product No. | Product Name | Qty | Item No. | Item Name | Qty |
--------------------------------------------------------------------------
W00001   | P0000001    | Product_1    |  6  | I000001  | Item_1    |  2  |
         |             |              |     | I000002  | Item_2    |  2  |
         |             |              |     | I000003  | Item_3    |  2  |
--------------------------------------------------------------------------
                                                           Total   :  6  |
--------------------------------------------------------------------------
W00002   | P0000002    | Product_2    |  7  | I000001  | Item_1    |  3  |
         |             |              |     | I000004  | Item_4    |  4  |
--------------------------------------------------------------------------
                                                           Total   :  7  |
--------------------------------------------------------------------------

如您所见,产品由多个项目组成。到目前为止,我可以更像上面的例子,但我的问题是如何显示上面的例子项目。我想在一行中显示项目。如何使用php显示?

1 个答案:

答案 0 :(得分:0)

如果您已经有2个表:一个用于产品,一个用于商品,您只需循环抛出产品一个,每个产品获得该产品所需的所有商品并在那里显示。

您的代码需要看起来像这样:

$products = get_products_from_db(); //How you normal get products from db.
foreach($products as $product) {
    $items = get_items_by_product_from_db($product['id']);   //get from db all items for a product.
    //foreach product we will need a new row.

    echo '<tr>';
    echo "<td>{$product['work_no']}</td>";    //and all the normal cells like this.
    //for item no. we will create a cell and inside it we will foreach items.
    echo "<td>";
    foreach($items as $item) {
        echo $item['item_no'] . '<br/>';//Or how it's called in db.
    }
    echo "</td>";
    //Exact the same with name and quantity.
    //For quantity also keep a counter so you can display the total
    echo '</tr>';
    //After this row create a new tr to display the total. I think you know how to do this.
}