How to create a json with several arrays in php - php

I have several regions in my database table, I want to create a JSON that has arrays of each region. something like this:
var regions = {
"region1": [
{ "lat": -1.325416, "lng": 36.669051 },
{ "lat": -1.244058, "lng": 36.730391 },
{ "lat": -1.392932, "lng": 36.768752 }
],
"region2": [
{ "lat": -1.244058, "lng": 36.730391 },
{ "lat": -1.392932, "lng": 36.768752 },
{ "lat": -1.169516, "lng": 36.895608 }
],
"region3": [
{ "lat": -1.392932, "lng": 36.768752 },
{ "lat": -1.169516, "lng": 36.895608 },
{ "lat": -1.390505, "lng": 36.810023 }
]
}
How do I do that? Thanks
This is my php code:
<?php
include 'conn.php';
$sql = "select lat,lon from regions";
$res = mysqli_query($conn,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('lat' => " ".$row[0],
'lng' => " ".$row[1]
));
}
$data = json_encode($result,JSON_NUMERIC_CHECK);
echo $data;
?>
It gives a json for all regions.

You can do something like this:
First, get all regions.
Then for each region you have, get the remaining data.
$finalResult = array();
foreach ($regions as $region) {
$sql = "SELECT lat, lon FROM regions WHERE regionid = $region['regionid'];";
$res = mysqli_query($conn,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result, array(
'lat' => " ".$row[0],
'lng' => " ".$row[1],
));
}
array_push($finalResult, array(
$region['regionName'] => $result,
));
}
echo json_encode($finalResult, JSON_NUMERIC_CHECK);

Related

Include variable into array if not empty inside foreach

Include the name variable if the value is not empty inside the foreach. I tried this method code below but it include outside the array. I want to include within the array.
Sample Code:
$load_array = array();
foreach($stmt->fetchAll() as $row){
$load_array[] = array(
'name' => $row['name'],
'start_location' => array(
'address' => $row['start_address'],
'coords' => array (
'lat' => floatval($row['start_lat']),
'lng' => floatval($row['start_lng']),
),
),
);
if(!empty($row['shift_start'])) { $load_array['shift_start'] = $row['shift_start'];}
if(!empty($row['shift_end'])) { $load_array['shift_end'] = $row['shift_end'];}
}
return json_encode($load_array);
Output code above:
{
"0": {
"name": "Ramon Macger",
"start_location": {
"address": "76 Spilman Street GORSGOCH SA40 8ZB",
"coords": {
"lat": 42.45188,
"lng": -83.12829
}
}
},
"1": {
"name": "Roberto",
"start_location": {
"address": "76 Spilman Street GORSGOCH SA40 8ZB",
"coords": {
"lat": 42.45188,
"lng": -83.12829
}
}
},
"shift_start": "14:00",
"shift_end": "17:00"
}
The output should be like this:
{
"0": {
"name": "Ramon Macger",
"start_location": {
"address": "76 Spilman Street GORSGOCH SA40 8ZB",
"coords": {
"lat": 42.45188,
"lng": -83.12829
}
},
"shift_start": "14:00",
"shift_end": "17:00"
},
"1": {
"name": "Roberto",
"start_location": {
"address": "76 Spilman Street GORSGOCH SA40 8ZB",
"coords": {
"lat": 42.45188,
"lng": -83.12829
}
},
"shift_start": "14:00",
"shift_end": "17:00"
},
}
The shift_start and shift_end should be within the array not outside. My code is working in 1 array only and not on the foreach. However, it doesn't working within for each.
You need to add shift_start and shift_end values into the data array before you push it into $load_array. Something like this:
foreach($stmt->fetchAll() as $row){
$data = array(
'name' => $row['name'],
'start_location' => array(
'address' => $row['start_address'],
'coords' => array (
'lat' => floatval($row['start_lat']),
'lng' => floatval($row['start_lng']),
),
),
);
if(!empty($row['shift_start'])) {
$data['shift_start'] = $row['shift_start'];
}
if(!empty($row['shift_end'])) {
$data['shift_end'] = $row['shift_end'];
}
$load_array[] = $data;
}

Restful API throw unexpected output in codeigniter

controller:
<?php
require APPPATH . '/libraries/REST_Controller.php';
use Restserver\Libraries\REST_Controller;
class User extends REST_Controller
{
function __construct()
{
parent::__construct();
$this->load->database();
}
function country_state_get()
{
$this->db->select('id,name');
$this->db->from('countries');
$sql = $this->db->get();
$data = $sql->result_array();
foreach($data as $row)
{
$this->db->select('id,name');
$this->db->from('states');
$this->db->where('country_id',$row['id']);
$sqls = $this->db->get();
$data2 = $sqls->result_array();
}
$result= [
"Country" => $data,
"state" => $data2
];
$this->response($result, 200);
}
}
unexpected output:
{
"Country": [
{
"id": "1",
"name": "Afghanistan"
},
{
"id": "2",
"name": "Albania"
},
{
"id": "3",
"name": "Algeria"
}
]
}
expected output:
{
"Country": [
{
"id": "1",
"name": "Afghanistan",
"state": ["Badakhshan", "Badghis", "Baghlan"]
},
{
"id": "2",
"name": "Albania",
"state": ["Berat", "Dibres", "Durres"]
},
{
"id": "3",
"name": "Algeria",
"state": ["Adrar", "Ain Defla", "Ain Temouchent"]
}
]
}
I have to create simple country and state api using codeigniter framework. Here I am getting unexpected output as I mention above. when I hit the url on my localhost server it throw unexpected out but my expected output is different. So, How can I do this? Please help me.
Thank You
Update your country_state_get function with below function code
function country_state_get()
{
$this->db->select('id,name');
$this->db->from('countries');
$sql = $this->db->get();
$data = $sql->result_array();
foreach($data as $key => $row)
{
$this->db->select('id,name');
$this->db->from('states');
$this->db->where('country_id',$row['id']);
$sqls = $this->db->get();
$data2 = $sqls->result_array();
$data[$key]['state'] = $data2;
}
$result= [ "Country" => $data ];
$this->response($result, 200);
}

How create json encode by one object with mutiple array in php?

I have two table names are channel and department.
$result = mysql_query("SELECT * FROM channels");
while($json = mysql_fetch_assoc($result)){
$fetch = mysql_query("SELECT * FROM departments where channelid='".$json['id']."'");
$json2 = array();
while ($row = mysql_fetch_array($fetch)){
$json2[] = array('departmentname' => $row["departmentname"],'departmentid' => $row["did"]
);
}
$json['department'] = $json2;
echo json_encode($json);
}
Ouput:
{
"id": "1",
"channelname": "con",
"channelurl": "http:\/\/xxx.net\/YY\/",
"department": [
{
"departmentname": "xxx Travel",
"departmentid": "1"
},
{
"departmentname": "xxxx Virtual Assist",
"departmentid": "2"
},
"departmentname": "xxx Premier",
"departmentid": "3"
},
{
"departmentname": "xxxx Events",
"departmentid": "4"
}
]
}{
"id": "2",
"channelname": "Slim",
"channelurl": "http:\/\/xxxxx.net\/slim\/",
"department": [
{
"departmentname": "Virtualvideo",
"departmentid": "5"
}
]
}
Expected Result:
[
{
"id": "1",
"channelname": "xxxxx",
"channelurl": "http://XXXXX.net/yyy/",
"department": [
{
"departmentname": "XXX Travel",
"departmentid": "1"
},
{
"departmentname": "XXXX Virtual Assist",
"departmentid": "2"
},
{
"departmentname": "XXXX Premier",
"departmentid": "3"
},
{
"departmentname": "XXXX Events",
"departmentid": "4"
}
]
},
{
"id": "2",
"channelname": "Slim",
"channelurl": "http://XXXXXX.net/slim/",
"department": [
{
"departmentname": "Virtual video",
"departmentid": "5"
}
]
}
]
try this:
$json_channel = array();
$json_final = array();
$result = mysql_query("SELECT * FROM channels");
while($json = mysql_fetch_assoc($result))
{
$fetch = mysql_query("SELECT * FROM departments where channelid='".$json['id']."'");
$json_dept = array();
while ($row = mysql_fetch_array($fetch))
{
$json_dept[] = array('departmentname' => $row["departmentname"],'departmentid' => $row["did"]);
}
$json_channel = array('id' => $json["ch_id"], 'channelname' =>$json["channelname"], 'department' => $json_dept);
$json_final[] = $json_channel;
}
echo json_encode($json_final);
$output = array();
$result = mysql_query("SELECT * FROM channels");
while($json = mysql_fetch_assoc($result)){
$fetch = mysql_query("SELECT * FROM departments where channelid='".$json['id']."'");
$json2 = array();
while ($row = mysql_fetch_array($fetch)){
$json2[] = array('departmentname' => $row["departmentname"],'departmentid' => $row["did"]
);
}
$json['department'] = $json2;
$output[] = $json;
}
echo json_encode($output);

mixare json, how to configure?

$query = "SELECT id, latitude, longitude, elevation, title, distance, has_detail_webpage, webpage, info FROM korban";
$q=mysql_query($query);
//echo $query;
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
From this code, it will generate like this,
[
{"id":"1","latitude":"-77.036519","longitude":"77.036519","elevation":"0","title":"coba","distance":null,"has_detail_webpage":"0","webpage":"0","info":"0"},
{"id":"3","latitude":"12","longitude":"42","elevation":"21","title":"213","distance":"12","has_detail_webpage":"1","webpage":"12","info":"12"},
{"id":"32","latitude":"","longitude":"","elevation":null,"title":null,"distance":null,"has_detail_webpage":"1","webpage":null,"info":null}
]
But I want something like this,
{ "status": "OK", "num_results": 3, "results":
[ { "id": "2833", "lat": "41.359288", "lng": "-73.646850", "elevation": "53", "title": "Target4", "distance": "1.756", "has_detail_page": "1", "webpage": "" },
{ "id": "2821", "lat": "41.359768", "lng": "-73.646870", "elevation": "0", "title": "Target2", "distance": "1.771", "has_detail_page": "0", "webpage": "" },
{ "id": "2829", "lat": "41.359820", "lng": "-73.646870", "elevation": "0", "title": "Target3", "distance": "1.545", "has_detail_page": "1", "webpage": "" }
] }
How can I do it?
Fetch all your results or do it row by row. Choose yourself. En create the json array afterwards. You also might want to look at your use of mysql_* functions. As they are deprecated now. And you should really switch to MySQli/PDO
$result = array();
while($row = mysql_fetch_assoc($q)) {
$result[] = $row;
}
$output = array('status' => 'OK' , 'num_results' => count($result), 'results' => $result);
echo json_encode($output);
To add the structure you wish to have in your json, first you must create that structure from php before encoding it to json.
$objects = array();
while ($r = mysql_fetch_associ($rs) {
$a = new stdClass();
$a->status = $r['status'];
...
$a->results = array('id' => $r['id']....)
$objects[] = $a;
}
echo json_encode($objects);
$query = "SELECT id, latitude, longitude, elevation, title, distance, has_detail_webpage, webpage, info FROM korban";
$q=mysql_query($query);
$output = array();
if($q) {
$output['status'] = 'OK';
}
$output['num_results'] = mysql_num_rows($q);
while($e=mysql_fetch_assoc($q)) {
$output['results'][]= array (
'id' => $e['id'],
'lat' => $e['latitude'],
'lng' => $e['longitude'],
'elevation' => $e['elevation'],
'title' => $e['title'],
'distance' => $e['distance'],
'has_detail_page' => $e['has_detail_webpage'],
'webpage' => $e['webpage'],
);
}
print(json_encode($output));

Output from mySql a two dimensional Json but with duplicates

mySql outputs this:
As you can see row 3 and 4 has duplicates so I want to merge these duplicates when I output my Json. To be exact I want my json to be like this:
[
{
"name": "The Crane Bar",
"lat": "53.2692",
"lng": "-9.06151",
"events": [
{
"name": "Traditional music session",
"info": null
}
]
},
{
"name": "Taaffes Bar",
"lat": "53.2725",
"lng": "-9.05321",
"events": [
{
"name": "6 Nations, Italy VS Ireland",
"info": null
}
]
},
{
"name": "a house",
"lat": "37.4401",
"lng": "-122.143",
"events": [
{
"name": "Party at Palo Alto",
"info": "Some info about the party"
},
{
"name": "2gdfgdf",
"info": "2gdfgdfgdf"
}
]
}
]
You know use one one location_name, lat and lng and have nested the event_name and post_content (as info here).
Thanks!
Based on your comment, you want the results to be nested, so when you generate the JSON, iterate over the rows and build a nested result list in PHP:
$result = array();
$item = null;
for ($i = 0; $i < count($rows); ++$i) {
$row = $rows[$i];
if ($item === null) {
$item = array('location' => $row['location'], 'events' => array());
}
$item['events'][] = array('name' => $row['event_name']);
if ($i == count($rows) - 1 || $row['location'] != $rows[$i + 1]['location']) {
$result[] = $item;
$item = null;
}
}
echo json_encode($result); // JSON-encoded data
Now each location will have an events list with one or more entries.

Categories