I would like to convert my PHP script to JSON to return a specific structure with parent and child. I searched some similar questions here, but unfortuntly i didn’t find a correct way to solve my doubt:
- How to create json array php with childs
- php json parse access child values
- Php echo json array with children
- How to select JSON (dynamic) Parent and Child in PHP?
I have a database table that call tbl_countries that’s similar to the structure below:
id | countryID | country | city
-----------------------------------------
1 | 1 | Greece | Athens
2 | 1 | Greece | Thessalonica
3 | 2 | Italy | Rome
4 | 2 | Italy | Milan
What i would like to do is convert my php script to return a json structure as below:
[{
"id": 1,
"text": "Greece",
"children": [{
"id": "Athens",
"text": "Athens"
}, {
"id": "Thessalonica",
"text": "Thessalonica"
}]
}, {
"id": 2,
"text": "Italy",
"children": [{
"id": "Milan",
"text": "Milan"
}, {
"id": "Rome",
"text": "Rome"
}]
}]
Below is the php script that i’m trying to convert like json structure above. This script, when executed, return information correctly, but not like the structure that i would like to has:
include 'config.php';
$stmt = $mysqli -> prepare('SELECT countryID, country, city FROM tbl_countries');
$stmt -> execute();
$stmt -> store_result();
$stmt -> bind_result($countryID, $country, $city);
$json = array();
while ($stmt -> fetch()) {
$json[] = array("id" => $countryID, "text" => $country, "children" => [array("id" => $city, "text" => $city)]);
}
header('Content-Type: application/json');
print_r(json_encode($json, JSON_UNESCAPED_UNICODE));
In this case how can i improve my php script to return a similar json structure above?