简体   繁体   English

mysql 到 json 使用 php。 嵌套对象

[英]mysql to json using php. Nested objects

Good Afternoon, I am trying to get these results into arrays in PHP so that I can encode them into json objects and send them to the client.下午好,我正在尝试将这些结果输入 PHP 中的 arrays 以便我可以将它们编码为 json 对象并将它们发送给客户端。 The results of the query look like this:查询结果如下所示:

   id   name    hours   cat status
3bf JFK Int 24  pass    open
3bf JFK Int 24  std closed
3bf JFK Int 24  exp open
5t6 Ohm CA  18  pass    closed
5t6 Ohm CA  18  std closed
5t6 Ohm CA  18  std2    open
5t6 Ohm CA  18  exp open
...

I would like for the json objects to look like this:我希望 json 对象看起来像这样:

{ "id": "3bf", "name": "JFK Int", "cats":
    { [ { "cat": "pass", "status": "open" },
        { "cat": "std", "status": "closed" },
        { "cat": "exp", "status": "open" } ] }
{ "id": "5t6", "name": "Ohm CA", "cats":
    { [ { "cat": "pass", "status": "closed" },
        { "cat": "std", "status": "closed" },
        { "cat": "std2", "status": "open" } ],
        { "cat": "exp", "status": "open" } ] }

I have succesfully connected to mysql and exported using json_encode using flat tables but this part I do not know how to do in PHP.我已成功连接到 mysql 并使用 json_encode 使用平面表导出,但这部分我不知道如何在 PHP 中执行。 Thanks.谢谢。

This is the code that I have.这是我拥有的代码。 This returns an array of json objects but it is flat, not nested:这将返回一个 json 对象数组,但它是扁平的,不是嵌套的:

$SQL = "SELECT id, name, hours, cat, status FROM bwt.vewPortCats";

$result = mysql_query($SQL);

$arr = array();
    while ($row = mysql_fetch_assoc($result)) {
        $arr[] = $row;}

$json = json_encode($arr);

echo $json;

The data itself is from a view that combines the tables ports and cats.数据本身来自结合了表端口和猫的视图。

what you could do (sorry, not the best code I could write... short on time, ideas, and energy ;-) is something like this (I hope it still conveys the point): 你能做什么(对不起,不是我写的最好的代码......时间短,想法和精力;-)就是这样的(我希望它仍然传达了这一点):

$SQL = "SELECT id, name, hours, cat, status FROM bwt.vewPortCats";

$result = mysql_query($SQL);

$arr = array();
    while ($row = mysql_fetch_assoc($result)) {

        // You're going to overwrite these at each iteration, but who cares ;-)
        $arr[$row['id']]['id'] = $row['id'];
        $arr[$row['id']]['name'] = $row['name'];

        // You add the new category
        $temp = array('cat' => $row['cat'], 'status' => $row['status']);

        // New cat is ADDED
        $arr[$row['id']]['cats'][] = $temp;
    }


$base_out = array();

// Kind of dirty, but doesn't hurt much with low number of records
foreach ($arr as $key => $record) {
    // IDs were necessary before, to keep track of ports (by id), 
    // but they bother json now, so we do...
    $base_out[] = $record;
}

$json = json_encode($base_out);

echo $json;

Haven't had the time to test or think twice about it, but again, I hope it conveys the idea... 没有时间对它进行测试或三思而后行,但我希望它能传达出这个想法......

With thanks to @maraspin, I have got my below code:感谢@maraspin,我得到了以下代码:

function merchantWithProducts($id)
    {
        if (
            !empty($id)
        ) {

            //select all query
            $query = "SELECT
                     m.id as 'mMerchantID', m.name as 'merchantName', m.mobile, m.address, m.city, m.province,
                     p.id as 'ProductID', p.merchantId as 'pMerchantID', p.category, p.productName, p.description, p.price, p.image, p.ratingCount 
                FROM " . $this->table_name . " m 
                JOIN by_product p 
                ON m.id = p.merchantId 
                WHERE m.id = :id 
                GROUP BY m.id";

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

            // sanitize
            //  $this->id = htmlspecialchars(strip_tags($this->id));

            // bind values
            $stmt->bindParam(":id", $this->id);

            try {
                $success = $stmt->execute();

                if ($success === true) {

                    $results = $stmt->fetchAll();
                    
                    $this->resultToEncode = array();

                    foreach ($results as $row) {
                       
                        $objItemArray = array(
                            "merchantID" => $row->mMerchantID,
                            "merchantName" => $row->merchantName,
                            "mobile" => $row->mobile,
                            "address" => $row->address,
                            "city" => $row->city,
                            "province" => $row->province, 
                            "product" => array(
                                "productID" => $row->ProductID,
                                "pMerchantID" => $row->pMerchantID,
                                "category" => $row->category,
                                "productName" => $row->productName,
                                "description" => $row->description,
                                "price" => $row->price,
                                "image" => $this->baseUrl . 'imagesProducts/' . $row->image,
                                "ratingCount" => $row->ratingCount
                            )
                        );

                        
                        array_push($this->resultToEncode, $objItemArray);
                    }

                    http_response_code(200);
                    $httpStatusCode = '200 OK';
                    $pass = true;

                    // return json_encode($resultToEncode);
                } else {
                    http_response_code(204);
                    $httpStatusCode = '204 No Content';
                    $pass = false;
                    $this->resultToEncode = 'No Record Found';
                }
            } catch (PDOException $pdoEx) {
                http_response_code(500); // internal server error.
                $httpStatusCode = '500 Internal Server Error';
                $pass = false;
                $this->resultToEncode = $pdoEx->getCode();
            } catch (Exception $ex) {
                // return $ex->getMessage();
                http_response_code(404); // 404 Not Found.
                $httpStatusCode = '404 Not Found';
                $pass = false;
                $this->resultToEncode = $ex->getMessage();
            }
        } else {
            http_response_code(400);
            $httpStatusCode = '400 bad request';
            $pass = false;
            $this->resultToEncode = 'User id not specified';
        }
        echo json_encode(array('passed' => $pass, 'Response' => $httpStatusCode, 'result' => $this->resultToEncode));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM