Create JSON file and display - php

I want to create a JSON file based in MySQL data but for some reasons my code is not working at all(I dont have any errors)
$results= $panel->query('SELECT * FROM servers ORDER BY id ASC;')->fetch_all();
$data = array();
foreach ($results as $row) {
$data[] = $row;
}
$json_string = json_encode($data);
$file = 'servers.json';
file_put_contents($file, $json_string);
What I want:
{
"ID": [
"IPOFTHESERVERFROMDATABASE",
PORTFROMDATABASE,
"NAMEFROMDATABASE"
],
..
}
What I'm getting:
[["ID","NAME","IP","PORT","RCON"]]

You are not putting anything into the $data array.
Change the code as below to load the rows into the $data array before json_encode()ing it
$results= $panel->query('SELECT * FROM servers ORDER BY id ASC;')->fetch_all();
$data = array();
foreach ($results as $row) {
$data[] = $row;
}
$json_string = json_encode($data);
$file = 'servers.json';
file_put_contents($file, $json_string);
Or as Ray says below, as you have used a fetchAll you could probably do without the foreach loop and do
$results= $panel->query('SELECT * FROM servers ORDER BY id ASC;')->fetch_all();
$json_string = json_encode($results);
$file = 'servers.json';
file_put_contents($file, $json_string);
EDIT: The output you wanted?
You say you want
{
"ID": [
"IP",
PORT,
"NAME"
],
"ID": [
"IP",
PORT,
"NAME"
]
}
which of course is not possible as you have 2 keys/properties with the same name i.e. "ID"
$results= $panel->query('SELECT * FROM servers ORDER BY id ASC;')->fetch_all();
$data = array();
foreach ($results as $row) {
$data[$row[0]] = [$row[2],$row[3],$row[1]];
}
$json_string = json_encode($data);
$file = 'servers.json';
file_put_contents($file, $json_string);

Related

Push array into array then encode - PHP

I'm trying to combine a few mySQL queries in a single PHP and push it all into a single JSON object.
So, I'm starting with the first query...like this:
$data=[];
$response = $stmt->fetchAll(PDO::FETCH_ASSOC);
$final_count = count($response);
$data['count'] = $final_count;
If I then do echo json_encode($data); I get a nicely formatted object like: {"count":61}
I then have a second query that I put the results through a loop, like so:
$response = $stmt->fetchAll(PDO::FETCH_ASSOC);
$items = array();
foreach ($response as &$value) {
$items[] = $value['date_added'];
}
echo json_encode($items);
And I get my nice set of dates:
["2017-06-24 00:08:58","2017-06-26 15:01:48","2017-06-27 15:01:48","2017-06-28 23:19:41","2017-06-29 01:38:07","2017-06-30 00:08:58"]
Here's the question, how do I get this all back together like so:
{
"count": 61,
"dates": [
"2017-06-24 00:08:58",
"2017-06-26 15:01:48",
"2017-06-27 15:01:48",
"2017-06-28 23:19:41",
"2017-06-29 01:38:07",
"2017-06-30 00:08:58"
]
}
You could use
$myData['count'] = $final_count;
$myData['dates'] = $items
echo json_encode($myData);
$data=[];
$response = $stmt->fetchAll(PDO::FETCH_ASSOC);
$final_count = count($response);
// first store count in `$data`
$data['count'] = $final_count;
$data['dates'] = [];
$response = $stmt->fetchAll(PDO::FETCH_ASSOC);
// next, store dates in subarray of `$data`
foreach ($response as &$value) {
$data['dates'][] = $value['date_added'];
}
// finally encode everything
echo json_encode($data);
Of course you can use array_merge of all your collected data.
Or:
$data=[];
// get $final_count
$data['count'] = $final_count;
// ... do some more stuff
// load items from db
$data['dates'] = $items;
echo json_encode($data);

How do I structure my data into the required format while encoding it into JSON?

I am working on an application that needs google charts to display results off MySql Database. How do I structure my data into the required format while encoding it into JSON?
This is my code so far:
$con=mysql_connect("localhost","root","") or die("Failed to connect with database!!!!");
mysql_select_db("su_data", $con);
$result = mysql_query("SELECT * FROM chart");
$data = array();
while ($row = mysql_fetch_object($result)) {
// Generate the output in desired format
$data[]=$row;
}
I want it to look like this:
{
"cols": [
{"id":"","label":"Topping","pattern":"","type":"string"},
{"id":"","label":"Slices","pattern":"","type":"number"}
],
"rows": [
{"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
{"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
]
}
I dont know in php but in Java Web application , we use Gson (google library) at controller and At view level we used jersey library to convert objects into JSON
$result = mysql_query("SELECT * FROM chart");
$data = array();
$cols[]=array('label'=>"Month",'type'=>'string');
$cols[]=array('label'=>"Actual 2013",'type'=>'number');
$cols[]=array('label'=>"Actual 2014",'type'=>'number');
$cols[]=array('label'=>"Forecast 2014",'type'=>'number');
while ($row_result = mysql_fetch_assoc($result)) {
$c[] = array('v'=>$row_result['month'], 'f'=>null);
$c[] = array('v'=>$row_result['actual_2013'], 'f'=>null);
$c[] = array('v'=>$row_result['actual_2014'], 'f'=>null);
$c[] = array('v'=>$row_result['forecast_2014'], 'f'=>null);
$rows[]=array('c'=>$c);
$data = array(
'cols' => $cols,
'rows' => $rows);
unset($c);}
// echo '<pre>';
// print_r($data);
$json_data = json_encode($data);
//echo '<pre>';
// echo $json_data;
file_put_contents('sample.json', $json_data);

How to create a JSON array using PHP

My JSON data looks like this:
[
{
"email":"test#test.com",
"firstName":"test",
"lastName":"test",
"value":"test#test.com",
"tokens":"test#test.com"
},
{
...
}
]
and php data to create json file looks like this:
<?php
session_start();
include('connection.php');
$userId = $_SESSION['sess_user_id'];
$act = $_POST['action'];
$sth = mysql_query("SELECT email, firstName, lastName, email AS value, email AS tokens FROM User");
$rows = array();
while($r = mysql_fetch_assoc($sth))
{
$rows[] = $r;
}
$fp = fopen('./test.json', 'w');
fwrite($fp, json_encode($rows));
fclose($fp);
?>
When a user is added to the database, it runs this php code:
$file = './test.json';
$data = json_decode(file_get_contents($file), true);
$newdata = array('email'=>$email, 'firstName' => $firstName, 'lastName'=>$lastName, 'value'=>$email, 'tokens'=>$email);
$data[] = $newdata;
file_put_contents($file, json_encode($data));
I want the my JSON file to look like this:
[
{
"email":"test#test.com",
"firstName":"test",
"lastName":"test",
"value":"test#test.com",
"tokens":[
"test#test.com"
]
}
]
I tried to figure this out, but I couldn't. Please help?
php handles arrays different than javascript (which differentiates between objects and arrays).
$newdata = array(
'email'=>$email,
'firstName' => $firstName,
'lastName'=>$lastName,
'value'=>$email,
'tokens'=>array($email)
);
should do it.

Php json generation for multiple records

I am trying to create a json using php
while ($info = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$id = stripslashes($info['id']);
$pricedol = stripslashes($info['pricedol']);
$final_result = array('id' => $id,'pricedol' => $pricedol );
}
$json = json_encode($final_result);
echo $json;
This is giving the following output
{
"id": 14567,
"pricedol": 15.57
}
But i have couple of records in the db...i want the following output
{
"id": 14567,
"pricedol": 15.57
},
{
"id": 4567,
"pricedol": 55.25
},
One more thing...do i need to serialize before parsing in jquery
You could create a multi-dimensional array and use json_encode on that array:
$final_result = array();
while ($info = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$id = stripslashes($info['id']);
$pricedol = stripslashes($info['pricedol']);
$final_result[] = array('id' => $id,'pricedol' => $pricedol);
}
$json = json_encode($final_result);
echo $json;

Too much JSON info

I am using the following to convert data from mysql to JSON:
$sql = "select img_name from user_gallery_images where user_id=$_SESSION[user_id]";
$response = array();
$posts = array();
$result = $mysqli->query($sql);
while($row = $result->fetch_array()){
$file=$row['img_name'];
$fileDir = "gallery/$file.jpg";
$posts[] = array('thumb'=> $fileDir, 'image'=> $fileDir);
}
$response['posts'] = $posts;
$fp = fopen('/home/public_html/users/'.$settings[username].'/gallery/gallery.json', 'w');
$jsonData = stripslashes(json_encode($response));
fwrite($fp, $jsonData);
fclose($fp);
Which works well and creates e.g.
{"posts":
[
{"thumb":"gallery/tess1367386438.jpg","image":"gallery/tess1367386438.jpg"},
{"thumb":"gallery/tess1367386538.jpg","image":"gallery/tess1367386538.jpg"}
]
}
But, the JQuery plug in i'm using it with won't read it with the outer "posts" container
QUESTION:
How can I strip the outer "posts" container in the JSON to produce only:
[
{"thumb":"gallery/tess1367386438.jpg","image":"gallery/tess1367386438.jpg"},
{"thumb":"gallery/tess1367386538.jpg","image":"gallery/tess1367386538.jpg"}
]
Try
$jsonData = json_encode($response['posts']);

Categories