Creating nested JSON using PHP MySQL Creating nested JSON using PHP MySQL json json

Creating nested JSON using PHP MySQL


To efficiently group the subarray data, you should implement temporary keys. cityId is a suitable value to group by -- because cityNames may intentionally duplicate in the future but cityId must never un/intentionally duplicate in your database table.

When each new cityId is encountered, the conditional isset() call will determine whether a new/full set of data should be stored, or if data should merely be appended to the subarray.

I am calling array_slice() since it cuts down on unnecessary syntax / code-bloat.

After iterating through all of the rows, you can reindex the $result array, nest it inside runBasedOnCity, and add the status element.

I'll show my demo with PRETTY_PRINT so that it is easier to read, but in your actual code, you should remove the parameter. Also, a word of advice -- try to keep your variable names brief for improved readability.

Code: (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));

Output:

'{    "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"                }            ]        }    ]}'

After explaining how you wanted to preserve the id values in the subarrays, here is that solution:

Code: (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));