如何在PHP中基于某些分组将mysql查询的结果拆分为多个数组?

时间:2019-04-27 16:38:15

标签: php mysql arrays json database

我有php API (使用PDO)。我从客户端获取一些数据,并对其应用 mysql 查询,并从数据库接收查询结果。现在,我想要的是将此查询结果拆分为多个数组(多维数组)。

就像我将购物车的Item(11,12,13,17,17,18,19)ID发送到数据库查询一样,

"SELECT s.SparePartID, s.Name, s.VendorID, v.CompanyName 
FROM sparepart s 
INNER JOIN users v
ON v.VendorID= s.VendorID
WHERE s.SparePartID IN ('11', '12','13', '17', '18', '19')"

此查询结果如下:

+-------------+---------+----------+---------------------+
| SparePartID |   Name  | VendorID |     CompanyName     |
+=============+=========+==========+=====================+
|     11      |  Tyres  |    48    | Master Automotives  |
+-------------+---------+----------+---------------------+
|     12      |  Lights |    48    | Master Automotives  |
+-------------+---------+----------+---------------------+
|     13      |  Wheels |    48    | Master Automotives  |
+-------------+---------+----------+---------------------+
|     17      |  Torch  |    50    | *Repair Solutions*  |
+-------------+---------+----------+---------------------+
|     18      |   Lamp  |    50    | *Repair Solutions*  |
+-------------+---------+----------+---------------------+ 
|     19      | Camera  |    50    | *Repair Solutions*  |
+-------------+---------+----------+---------------------+

现在,我想根据其公司名称将其保存为组数组。因为此数据中有 2个不同的公司名称,所以我想将此数据保存在2个数组的数组中,否则组数应等于与众不同公司名称。

所以我希望分解,如

[

"Group1": [

{
"SparePartID": "11",
"Name" : "Tyres",
"VendorID": "48",
"Company" : "Master Automotives"
},

{
"SparePartID": "12",
"Name" : "Lights",
"VendorID": "48",
"Company" : "Master Automotives"
},

{
"SparePartID": "13",
"Name" : "Wheels",
"VendorID": "50",
"Company" : "Master Automotives"
}

]


"Group2": [

{
"SparePartID": "17",
"Name" : "Torch",
"VendorID": "50",
"Company" : "*Repair Solutions*"
},

{
"SparePartID": "18",
"Name" : "Lamp",
"VendorID": "50",
"Company" : "*Repair Solutions*"
},

{
"SparePartID": "19",
"Name" : "Camera",
"VendorID": "50",
"Company" : "*Repair Solutions*"
}


]


]

这是我的 show_cart.php 的PHP API代码,我想对其进行修改以获得上述结果:

<?php

include_once '../config/database.php';
include_once '../objects/product.php';

$database = new Database();
$db = $database->getConnection();
$product = new Product($db);

// get posted data
$json = file_get_contents("php://input");
$data = json_decode($json, true);
// query products
$stmt = $product->cart($data);
$num = $stmt->rowCount();

// check if more than 0 record found
if($num>0){
    $products_arr=array();
    $products_arr["records"]=array();
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row);
        $product_item=array(
            "SparePartID" => $SparePartID,
            "Name" => $Name,
            "Price" => $Price,
            "VendorID" => $VendorID,
            "Company" => $Company
        );
        array_push($products_arr["records"], $product_item);
    }
    http_response_code(200);
    echo json_encode($products_arr);
} else{
    // set response code - 404 Not found
    http_response_code(404);
    echo json_encode(
        array("message" => "No Spare Parts found in shopping Cart ")
    );
}
?>

其中 product.php 代码为:

function cart($ids){
     $ids_arr = str_repeat('?,', count($ids) - 1) . '?';

     $query = "SELECT s.SparePartID, s.Name, s.VendorID, v.CompanyName FROM sparepart s INNER JOIN users v ON v.VendorID= s.VendorID WHERE s.SparePartID IN ({$ids_arr})";

    $stmt = $this->conn->prepare($query);
    // execute query
    $stmt->execute($ids);

    // return values from database
    return $stmt;
}

现在请任何人帮助我来建议如何根据公司名称划分结果?执行查询后,我应该修改查询还是修改结果数组吗?请帮助

2 个答案:

答案 0 :(得分:1)

只需更改此行:

array_push($products_arr["records"], $product_item);

对此:

$products_arr["records"][$product_item["Company"]][] = $product_item;

答案 1 :(得分:0)

尝试此查询:

SELECT s.SparePartID, s.Name, s.VendorID, v.CompanyName FROM sparepart s 
INNER JOIN users v ON v.VendorID= s.VendorID WHERE s.SparePartID IN 
({$ids_arr}) **GROUP BY v.CompanyName**