【问题标题】:How to split the result of a mysql query into multiple arrays on the basis of some grouping, in PHP?如何在 PHP 中基于某些分组将 mysql 查询的结果拆分为多个数组?
【发布时间】:2019-04-27 16:38:15
【问题描述】:

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

就像我将购物车 Item(11, 12, 13, 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 个数组的数组中,否则组数应等于 不同的 公司名称。

所以我希望将 resluts 分开例如:

[

"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;
}

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

【问题讨论】:

    标签: php mysql arrays json database


    【解决方案1】:

    只需更改此行:

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

    到这里:

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

    【讨论】:

      【解决方案2】:

      试试这个查询:

      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**
      

      【讨论】:

      • 这将为每个公司名称生成一行,而不是所需的结果。
      • 感谢 Paul Robert 的回复,但实际上这将导致每个公司名称只有一行数据。第一个答案解决了我的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多