Php 在2个循环内构建阵列

Php 在2个循环内构建阵列,php,arrays,loops,Php,Arrays,Loops,有人能帮我吗? 因为我想不出来 假设我有一个包含两个表的数据库,一个是category,一个是product category table cat_id category_name 1 animals 2 fruits 3 vegetables product table pro_id category_id product_name 1 2 mango 2

有人能帮我吗? 因为我想不出来

假设我有一个包含两个表的数据库,一个是category,一个是product

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
我试着在分类表上按类别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等,请根据需要进行调整。

如何从数据库中获取数据?我使用while($row\u cat=mysql\u fetch\u array($result\u cat){然后再次调用product using while并构建一个数组。}您的意思是在while内检索类别id($row\u cat=mysql\u fetch\u array($result\u cat)){我需要先构建数组吗?对于cat id?然后使用循环?}不需要while循环-只需使用第一个查询检索类别列表,然后使用foreach循环遍历每个类别。然后您会看到我使用第二个查询检索该类别id的产品,并循环使用另一个foreach循环的产品。