【问题标题】:Creating a nested array with looping in PHP and MySQL在 PHP 和 MySQL 中使用循环创建嵌套数组
【发布时间】:2013-03-13 06:53:54
【问题描述】:

我有 2 个 MySQL 表,我使用以下 SQL 语句提取数据:

分类:SELECT cat_id, cat_name FROM categories

产品:SELECT pro_id, pro_name, pro_category FROM products

当然,pro_categorycat_id 的外键

我想获取以下 JSON 数据:

"categories":[
    {
        "id": 1,
        "name": "Guitars",
        "products":[
            {
                "id": 1,
                "name": "Fender Statocaster"
            },
            {
                "id": 2,
                "name": "Gibson Les Paul"
            }
        ]
    },
    {
        "id": 2,
        "name": "Basses",
        "products":[
            {
                "id": 3,
                "name": "Fender Jazz Bass"
            },
            {
                "id": 4,
                "name": "MusicMan StingRay"
            }
        ]
    }   
]

所以我必须做一个类别数组,并为每个元素制作一个产品子数组(然后我会选择json_encode())。

遍历类别并创建第一个数组非常容易,但我完全不知道如何创建产品子数组...这是我的代码,问号是我停下来的地方,因为我没有不知道该怎么办:

$categories = array();
while ($row_rsCategories = mysql_fetch_assoc($rsCategories)) { 
    $categories[] = array(
        'id' => $row_rsCategories['cat_id'],
        'name' => $row_rsCategories['cat_name'],
        'products' => array(
            ???????
        ),
    );
}

请问,你能帮忙吗?
谢谢!

【问题讨论】:

    标签: php mysql loops multidimensional-array


    【解决方案1】:

    我使用JOIN 查询通过其类别ID 来订购产品,这样属于某个类别的产品就会聚集在一起。如果看到 cat_id 更改,则遍历结果数组并创建新类别。

    $db = new PDO($connectionString);
    
    $sql = "SELECT * FROM products t1 LEFT JOIN categories t2 ON t1.pro_category = t2.cat_id ORDER BY t2.cat_id";
    $stmt = $db->prepare($sql);
    if($stmt->execute())
    {
        $rows = $stmt->fetchAll();
        $currentCategory = NULL;
        $categories = array();
        foreach($rows as $r)
        {
            if ($currentCategory == NULL || $r['cat_id' != $currentCategory['id'])
            {
                $currentCategory = array(
                    'id' => $r['cat_id'],
                    'name' => $r['cat_name'],
                    'products' => array();
                );
                $categories[] = $currentCategory;
            }
            $currentCategory['products'][] = array(
                'id' => 'pro_id',
                'name' => 'pro_name',
            )
        }
    }
    else
    {
        var_dump($stmt->errorInfo());
    }
    

    【讨论】:

      【解决方案2】:
      $categories = array();
      while ($row_rsCategories = mysql_fetch_assoc($rsCategories)) { 
          $categories[$row_rsCategories['cat_id']] = array(
              'id' => $row_rsCategories['cat_id'],
              'name' => $row_rsCategories['cat_name'],
              'products' => array(),
          );
      }
      
      while ($row_rsProducts = mysql_fetch_assoc($rsProducts)) {
          $categories[$row_rsProducts['pro_category']]['products'][] = array(
               'id' => $row_rsProducts['pro_id'],
               'name' => $row_rsProducts['pro_name'],
          );
      }
      

      【讨论】:

        【解决方案3】:
        $categories = array();
        while ($row_rsCategories = mysql_fetch_assoc($rsCategories)) { 
        
            $product_array = array();
            $product_array_query = mysql_query("SELECT pro_id, pro_name, pro_category FROM products WHERE pro_category = '".$row_rsCategories['cat_id']."'");
        
            while($product_array_fetch = mysql_fetch_array($product_array_query)) {
        
               $product_array[] = array("id"=>$product_array_fetch['pro_id'],"name"=>$product_array_fetch['pro_name']);
        
            }                
        
            $categories[] = array(
                'id' => $row_rsCategories['cat_id'],
                'name' => $row_rsCategories['cat_name'],
                'products' => $product_array,
            );
        }
        

        【讨论】:

        • 谢谢,这行得通!!!多次调用产品查询会影响性能吗?
        • @Ivan:我认为您将不得不使用内部 for 循环。请考虑使用PHP PDOmysqli extentions 而不是默认的mysql_* 函数,因为它们不再被php 社区推荐并且容易受到mysql injection 等安全威胁的影响。
        猜你喜欢
        • 2012-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-31
        • 1970-01-01
        • 2019-01-10
        • 2017-05-30
        相关资源
        最近更新 更多