$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));
Related
I have a table for Talepler and Yonetim. Now Each talepler has his own users. and each user is mapped to that talepler by a field called user id. So how i can print out online users with total count in Talepler table by Count(*) with Join query.
Here my code with helper function. But i want with join.
$this->db->select('yonetim.id, yonetim.user, yonetim.onoff');
$this->db->from('yonetim');
$this->db->where('yonetim.onoff',1);
$query = $this->db->get();
$datam = array();
foreach ($query->result() as $data) {
$count = checkIfuserMax($data->id);
if($talepsay < 10 ) {
$datam[] = array(
'id' => $data->id,
'user' => $data->user,
'onoff' => $data->onoff,
'toplamtalep' => $count
);
}
}
echo json_encode($datam);
and here my helper function
function checkIfuserMax($id) {
$ci =& get_instance();
$ci->db->select('COUNT(*) as toplam');
$ci->db->where(array( 'hangiadmin' => $id, 'onaylayan' => null));
$ci->db->from('talepler');
$query = $ci->db->get();
$result = $query->result();
return $result[0]->toplam;
}
Finally here my json result
[
{
"id": "1",
"user": "user1",
"onoff": "1",
"toplamtalep": "13"
},
{
"id": "2",
"user": "user2",
"onoff": "1",
"toplamtalep": "0"
},
{
"id": "4",
"user": "user3",
"onoff": "1",
"toplamtalep": "2"
},
{
"id": "173",
"user": "user4",
"onoff": "1",
"toplamtalep": "6"
}
]
This code working properly. But i want to make this same result with "JOIN" query. Could you please help me about this query?
I need to show Mysql data in json nested array like
{
"status": true,
"categories": [
{
"id": "1",
"title": "Title 1",
},
{
"id": "2",
"title": "Title 2",
},
{
"id": "3",
"title": "Title 3",
}
]
}
Code I am trying is
$sql = "SELECT * FROM `categories`";
$res_data = mysqli_query($conn,$sql);
$rows = array();
while($row = mysqli_fetch_array($res_data)){
$rows[] = $row;
foreach($rows as $row){
$rows = ['id' => $row['id'], 'title' => $row['title']];
}
}
$data = array('status' => true, 'categories' => array($rows));
echo json_encode($data);
But what I get is only with one record in the nested array i.e
{
"status": true,
"categories": [
{
"id": "1",
"title": "Title 1",
}
]
}
How can I achieve my requirement?
If you want to avoid duplication, leave out the foreach loop and just write in the while loop:
$rows[] = ['id' => $ row ['id'], 'title' => $ row ['title']];
…because with the while loop, you already run through the row array.
You don't need any loops. Mysqli already returns a nested array which you can directly output to JSON
$res_data = $conn->query("SELECT id, title FROM `categories`")
echo json_encode(['status' => true, 'categories' => $res_data->fetch_all(MYSQLI_ASSOC)]);
I am trying to create dynamically a JSON from a MySQL, which seems fairly easy with this piece of code I found in this thread Create nested json object using php mysql.
However, I want to add before and after the $json_response some piece of JSON code.
The main code
$result = mysql_query("SELECT * FROM Places ");
$json_response = array(); //Create an array
while ($row = mysql_fetch_array($result))
{
$row_array = array();
$row_array['title'] = $row['title'];
$row_array['image_url'] = $row['image_url'];
$row_array['subtitle'] = $row['subtitle'];
$row_array['buttons'] = array();
$id = $row['id'];
$option_qry = mysql_query("SELECT * FROM Places where id=$id");
while ($opt_fet = mysql_fetch_array($option_qry))
{
$row_array['buttons'][] = array(
'type' => $opt_fet['type'],
'caption' => $opt_fet['caption'],
'url' => $opt_fet['url'],
);
}
array_push($json_response, $row_array); //push the values in the array
}
echo json_encode($json_response, JSON_PRETTY_PRINT);
Produces this JSON
[
{
"title": "Name of the place",
"image_url": "image.jpg",
"subtitle":Additional info",
"buttons": [
{
"type": "'url'",
"caption": "More Info",
"url": "https://some link "
}
]
},
{
"title": "Name of the place 2",
"image_url": "image2.jpg",
"subtitle":Additional info2",
"buttons": [
{
"type": "'url'",
"caption": "More Info",
"url": "https://some link 2"
}
]
}
]
I have somehow to add the following code before the already created JSON
{
"version": "v2",
"content": {
"messages": [
{
"type": "cards",
"elements":
And this code in the end
}
]
}
}
Pretty simple:
$final_json = [
"version" => "v2",
"content" => [
"messages" => [[
"type" => "cards",
"elements" => $json_response
]]
]
];
echo json_encode($final_json, JSON_PRETTY_PRINT);
Personally, I'd rename $json_response to $messages for clarity purposes.
While declaring array $json_response = array(); you can actually prepare it with your default values require like
$stdObj=new \stdClass();
$stdObj->version="V2";
$stdObj->content=(object)["messages"=>(object)["type"=>'cards','elements'=>$row_array['buttons']]];
echo json_encode($stdObj, JSON_PRETTY_PRINT);
I have problem to combining two array, here my sample code
$arr1 = [];
$data = $this->db->query("SELECT QUERY");
foreach ($data->result_array() as $row) {
$arr1[] = array(
"type" => "column",
"name" => $row['name'],
"legendText" => $row['name'],
"showInLegend" => true
);
}
$count = $this->db->query("SELECT QUERY");
foreach ($count->result_array() as $rows) {
$arr1[]["dataPoints"] = array(
"label" => $rows['data']
);
}
With this code, result is
[
{
"type": "column",
"name": "LA 1",
"legendText": "LA 1",
"showInLegend": true
},
{
"dataPoints": {
"label": "1"
}
}
]
I want to combine two array, So the output should be like this:
[
{
"type": "column",
"name": "LA 1",
"legendText": "LA 1",
"showInLegend": true,
"dataPoints": [{
"label": "1"
}]
}
]
Please someone help me to find out the easiest way to solve this issue.
The proper way to fix this would be to change your database queries to one which would return all the information in a single query.
$data = $this->db->query("SELECT a.*, b.datapoints FROM table1 a, table2 b....");
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);