php - 使用 PHP MySQL 创建嵌套的 JSON

标签 php mysql arrays json

我有一个返回某些字段的 SQL 查询,我正在使用 json_encode() 获取 JSON 格式的数据,但是我无法获取我想要的格式。

PHP代码

<?php

function data() {
    $runDistanceBasedOnCityQuery = "SELECT rc.id, rc.cityId, c.cityName, rc.runId, r.distance, rc.status FROM run_city rc INNER JOIN cities c ON c.id = rc.cityId INNER JOIN run_distance r ON r.id = rc.runId ORDER BY c.cityName";
    $runDistanceBasedOnCityResult = $db->prepare($runDistanceBasedOnCityQuery);
    $runDistanceBasedOnCityResult->bindParam(":cityId", $cityId, PDO::PARAM_INT);
    $runDistanceBasedOnCityResult->execute();
    $runDistanceBasedOnCityOutput = $runDistanceBasedOnCityResult->rowCount();
    if ($runDistanceBasedOnCityOutput > 0) {
        while ($runDistanceBasedOnCityRow = $runDistanceBasedOnCityResult->fetch(PDO::FETCH_ASSOC)) {
            $array1 = array($runDistanceBasedOnCityRow['runId'], $runDistanceBasedOnCityRow['distance'], $runDistanceBasedOnCityRow['status']);
            for ($i = 0; $i < sizeof($array1); $i++) {
                $array2 = array("id" => $runDistanceBasedOnCityRow['id'], "runId" => $runDistanceBasedOnCityRow['cityId'], $runDistanceBasedOnCityRow['cityName'] => $array1);
            }

            $finalResultRunDistanceBasedOnCity[] = $array2;
        }
        $responseRunDistanceBasedOnCity = $finalResultRunDistanceBasedOnCity;
    } else {
        $responseRunDistanceBasedOnCity = 'Runs not found';
    }

    $result = array("status" => true,
        "runsBasedOnCity" => $responseRunDistanceBasedOnCity
    );

    json($result);
}

function json($data) {
    header('Content-Type:application/json');
    if (is_array($data)) {
        echo json_encode($data);
    }
}
?>

我得到的JSON格式

"runsBasedOnCity": [
    {
        "id": "1",
        "runId": "1",
        "Bengaluru": [
            "2",
            "10k",
            "1"
        ]
    },
    {
        "id": "2",
        "runId": "1",
        "Bengaluru": [
            "1",
            "5k",
            "1"
        ]
    },
    {
        "id": "3",
        "runId": "1",
        "Bengaluru": [
            "5",
            "3k",
            "0"
        ]
    },
    {
        "id": "4",
        "runId": "2",
        "Chennai": [
            "1",
            "5k",
            "1"
        ]
    },
    {
        "id": "5",
        "runId": "2",
        "Chennai": [
            "2",
            "10k",
            "1"
        ]
    },
    {
        "id": "6",
        "runId": "2",
        "Chennai": [
            "4",
            "15k",
            "1"
        ]
    }
]

我需要的格式

"runsBasedOnCity": [
    {
        "id": "1",
        "cityId": "1",
        "Bengaluru": 
         [
            {
              runId : "2",
              distance : "10k",
              status : "1"
            },
            {
              runId : "1",
              distance: "5k",
              status : "1"
            },
            {
              runId : "5",
              distance : "3k",
              status : "0"
            }
        ]
     },
     {
        "id": "2",
        "cityId": "2",
        "Chennai": 
         [
            {
              runId : "1",
              distance : "5k",
              status : "1"
            },
            {
              runId : "2",
              distance: "10k",
              status : "1"
            },
            {
              runId : "4",
              distance : "15k",
              status : "1"
            }
        ]
     }

我想不出更好的方法,我对此很陌生,请帮助我。谢谢!

最佳答案

要有效地对子数组数据进行分组,您应该实现临时键。 cityId 是一个适合分组的值——因为 cityNames 将来可能有意重复,但 cityId 绝不能在您的数据库中无意/有意重复表。

当遇到每个新的 cityId 时,有条件的 isset() 调用将确定是否应该存储一组新的/完整的数据,或者是否应该只存储数据附加到子数组。

我正在调用 array_slice(),因为它减少了不必要的语法/代码膨胀。

遍历所有行后,您可以重新索引$result 数组,将其嵌套在runBasedOnCity 中,并添加status 元素.

我将使用 PRETTY_PRINT 展示我的演示,这样它更容易阅读,但在您的实际代码中,您应该删除该参数。另外,还有一点建议——尽量让您的变量名称简短,以提高可读性。

代码:(Demo)

$resultset = [
    ["id" => "1", "cityId" => "1", "cityName" => "Bengaluru", "runId" => "2", "distance" => "10k", "status" => "1"],
    ["id" => "2", "cityId" => "1", "cityName" => "Bengaluru", "runId" => "1", "distance" => "5k", "status" => "1"],
    ["id" => "3", "cityId" => "1", "cityName" => "Bengaluru", "runId" => "5", "distance" => "3k", "status" => "0"],
    ["id" => "4", "cityId" => "2", "cityName" => "Chennai", "runId" => "1", "distance" => "5k", "status" => "1"],
    ["id" => "5", "cityId" => "2", "cityName" => "Chennai", "runId" => "2", "distance" => "10k", "status" => "1"],
    ["id" => "6", "cityId" => "2", "cityName" => "Chennai", "runId" => "4", "distance" => "15k", "status" => "1"]
];

foreach ($resultset as $row) {
    if (!isset($result[$row["cityId"]])) {
        $result[$row["cityId"]] = array("id" => $row["id"], "cityId" => $row["cityId"], $row["cityName"] => array(array_slice($row,-3)));
    } else {
        $result[$row['cityId']][$row["cityName"]][] = array_slice($row,-3);
    }
}

if (!isset($result)) {   // don't need to check rowCount() at all
    $result = 'Runs not found';
} else {
    $result = array_values($result);
}

$result = array("status" => true, "runsBasedOnCity" => $result);

var_export(json_encode($result, JSON_PRETTY_PRINT));

输出:

'{
    "status": true,
    "runsBasedOnCity": [
        {
            "id": "1",
            "cityId": "1",
            "Bengaluru": [
                {
                    "runId": "2",
                    "distance": "10k",
                    "status": "1"
                },
                {
                    "runId": "1",
                    "distance": "5k",
                    "status": "1"
                },
                {
                    "runId": "5",
                    "distance": "3k",
                    "status": "0"
                }
            ]
        },
        {
            "id": "4",
            "cityId": "2",
            "Chennai": [
                {
                    "runId": "1",
                    "distance": "5k",
                    "status": "1"
                },
                {
                    "runId": "2",
                    "distance": "10k",
                    "status": "1"
                },
                {
                    "runId": "4",
                    "distance": "15k",
                    "status": "1"
                }
            ]
        }
    ]
}'

在解释了您希望如何在子数组中保留 id 值之后,解决方案如下:

代码:(Demo)

foreach ($resultset as $row) {
    if (!isset($result[$row["cityId"]])) {
        $result[$row["cityId"]] = array("cityId" => $row["cityId"], $row["cityName"] => array(array("id" => $row["id"])+array_slice($row,-3)));
    } else {
        $result[$row['cityId']][$row["cityName"]][] = array("id" => $row["id"])+array_slice($row,-3);
    }
}

if (!isset($result)) {   // don't need to check rowCount() at all
    $result = 'Runs not found';
} else {
    $result = array_values($result);
}

$result = array("status" => true, "runsBasedOnCity" => $result);
var_export(json_encode($result, JSON_PRETTY_PRINT));

关于php - 使用 PHP MySQL 创建嵌套的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49505372/

相关文章:

java - 如何检查Spring Boot使用的是什么数据库池?

mysql - 更新多个数据库的 Shell 脚本

c# - 当我向数组添加某些内容时,它不会向列表添加任何内容

javascript - JS : Loop forces ascending sorting, 如何保持定义的顺序?

php - yii语言本地化mysql表数据进入 View

php - 带有请求报价插件和 Woocommerce 示例的 Woocommerce 空购物车问题

mysql - 如何在订购前添加数字到时间(MySQL)

PHP Websocket 在测试中对用户进行身份验证(传递 session cookie)

php - 无法打开流 : Is a directory in

arrays - XPATH 通过一组可能的属性值选择