在 2 个循环内构建数组


building array inside 2 loops

有人可以帮助我吗?因为我想不通。

假设我有一个包含两个表的数据库,一个是类别,一个是产品

category table
cat_id         category_name
1          animals
2          fruits
3          vegetables

product table
pro_id       category_id    product_name
1            2             mango
2            3             beans
3            2             apple
4            1             cat

我尝试在类别表上按cat_id选择猫ID顺序当猫桌循环播放时....{我尝试使用cat_id在产品表上选择产品当产品表循环时..{我只想把它放在一个好的格式的数组中}

}

示例结果为

        Array
        (
            [fruits] => Array
                (
from cat_id -->  [2] => Array
                        (
                            [pro_id] => 1
                            [name] => mango
                        )           
from cat_id -->  [2] => Array
                         (  [id] => 3
                            [name] => apple
                        )
                ),
            [vegetables] => Array
                (
from cat_id -->  [3] => Array
                        (
                            [pro_id] => 2
                            [name] => beans
                        )           
                ),
            [animals] => Array
                (
from cat_id -->  [1] => Array
                        (
                            [pro_id] => 4
                            [name] => cat
                        )           
                )       
         )

我将首先检索类别并遍历这些类别,然后检索每个类别的产品。 像这样:

$result = Array();
$sql = "SELECT * FROM category ORDER BY category_name";
// db query here (however you are doing that)
foreach ($categories as $category)
    {
    $result[$category['category_name']] = Array();
    $sql = "SELECT * FROM product WHERE category_id = $category[cat_id] ORDER BY product_name";
    // db query here (however you are doing that)
    foreach ($products as $product)
        $result[$category['category_name']][$product['pro_id']] = $product['product_name'];
    }

这将为您提供如下输出:

Array(
    'fruits' => Array(
        1 => 'mango',
        3 => 'apple',
        )
     etc.

如果您需要保留类别 ID 等,请根据需要进行调整。