在2个循环中构建数组

时间:2014-12-08 21:55:12

标签: php arrays 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选择cat id order 而猫表正在循环.... { 我尝试使用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
                        )           
                )       
         )

1 个答案:

答案 0 :(得分:0)

我首先检索类别并循环浏览这些类别,然后检索每个类别的产品。类似的东西:

$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等,请根据需要进行调整。