How to make a JSON output like this? - php

My desired output
{"rowcount":4
[{"provider_id":"1","provider_name":"Crecent Computers","sub_name":["Hardware","Software","Networks"]}],[{"provider_id":"4","provider_name":"Testing Co. LLC","sub_name":["Hardware","Software","Networks"]}],[{"provider_id":"41","provider_name":"Itiology","sub_name":["Hardware","Software","Networks","All IT Services"]}],[{"provider_id":"42","provider_name":"ITiology","sub_name":["Hardware","Software","Networks","All IT Services","Website Design "]}]}
My desired output end
My current JSON output
{"rowcount":4,"0":[{"provider_id":"1","provider_name":"Crecent Computers","sub_name":["Hardware","Software","Networks"]}],"1":[{"provider_id":"4","provider_name":"Testing Co. LLC","sub_name":["Hardware","Software","Networks"]}],"2":[{"provider_id":"41","provider_name":"Itiology","sub_name":["Hardware","Software","Networks","All IT Services"]}],"3":[{"provider_id":"42","provider_name":"ITiology","sub_name":["Hardware","Software","Networks","All IT Services","Website Design "]}]}
JSON Output end
PHP CODE
$result = mysqli_query($con, "select * from service_provider where servicecategory_id = '1'");
if ($counter = mysqli_query($con, "select * from service_provider where servicecategory_id = '1'"))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($counter);
// Free result set
mysqli_free_result($counter);
}
$data_points = array();
$subcatArray = array();
$data_points["rowcount"] = $rowcount;
while($row = mysqli_fetch_assoc($result))
{
$subcatresult = mysqli_query($con, "SELECT sub_name, price FROM sub_services WHERE provider_id = " . $row['provider_id']);
while($subcatrow = mysqli_fetch_assoc( $subcatresult))
{
$subcatArray[] = $subcatrow['sub_name'];
unset($subcatrow);
$subcatrow = array();
}
$data_points[][] = [
'provider_id' => $row['provider_id'],
'provider_name' => $row['provider_name'],
'sub_name' => $subcatArray
];
// array_push("totalRow",$data_points, $point);
}
echo json_encode($data_points);
PHP CODE END

you desired output json is an invalid json. you can check this json out valid or not in the http://jsonviewer.stack.hu. json or xml has it's own patterns.

So i found out that my desired output is invalid. Sorry I'm new to PHP.
I removed this line
$data_points["rowcount"] = $rowcount;
and made this
$data_points[][] = [
'provider_id' => $row['provider_id'],
'provider_name' => $row['provider_name'],
'sub_name' => $subcatArray
];
into this
$data_points["Rows"][] = [
'provider_id' => $row['provider_id'],
'provider_name' => $row['provider_name'],
'sub_name' => $subcatArray
];
I got the output pretty much close to what i need. Thanks guys!

Related

fetch data from sql into php array returns nothing

I'm trying to json_encode the data that was fetched from SQL, however, when I stored it into PHP array, it didn't return any value. Is there any code that I am missing or are there limits to the array?
I tried json_encode() inside a loop but I need angular 4 to read the json file that was encoded from the php file. Also, I tried to check if the loop was working and it fetched the 56 rows from SQL but when I put it into the PHP array, the array was displaying a blank PHP file.
/location.php (TRY1)
$sql = "SELECT * FROM api_locations";
$result = mysqli_query($con, $sql);
$outp = array();
if(mysqli_num_rows($result) > 0)
{
while($data = $result->fetch_assoc()){
$location = $data['loc_name'];
$feature = $data['feature'];
$lat = $data['lat'];
$lng = $data['lng'];
$desc = $data['description'];
$hrs = $data['hrs'];
$min = $data['min'];
$rating = $data['rating'];
$max_b = $data['budget_maximum'];
$min_b = $data['budget_minimum'];
$outp[] = array(
"location" => $location,
"feature" => $feature ,
"lat" => $lat ,
"lng" => $lng ,
"description" => $desc ,
"hrs" => $hrs ,
"min" => $min ,
"rating" => $rating ,
"budget_maximum" => $max_b ,
"budget_minimum" => $min_b ,
);
}
echo json_encode($outp);
}
or i did the while loop the other way:
while ($data = mysqli_fetch_assoc($result)) {
$outp[] = $data;
}
NOTE: The $outp is still empty when doing json_encode.
I expect the output will be like this.
{"id":"1","loc_name":"Robinsons
Magnolia","lat":"123.1321","lng":"12.213","feature":"Shopping","description":"Happy
place to
shop","hrs":"1","min":"30","rating":"4","budget_maximum":"5000","budget_minimum":"100"}
...
{"id":"56","loc_name":"CHICHIHC","lat":"213.1213","lng":"12.23131","feature":"Entertainment","description":"Good place to make
kalokohan","hrs":"1","min":"30","rating":"4","budget_maximum":"100","budget_minimum":"50"}
But the real output was blank.
I also tried to do this
$sql = "SELECT *
FROM api_locations WHERE id<=9";
And this works. totally! but when it exceeds from 9. still not working.

How to encode json with multiple rows?

Before I begin, I have looked through other examples and Q&A's on multiple platforms but none of them seem to solve my problem. I am trying to return multiple rows from MySQL via a json. However, I have been unable to. The code below shows my attempt.
I get my responses via Postman. The first while returns only the last entry in the database, and the do-while returns all entries but doesn't encode the json properly, as the json outputs syntax error but the html part shows all entries.
<?php
$dashboard_content_token = $_REQUEST["dashboard_content_token"];
$token = "g4";
require(cc_scripts/connect.php);
$sql = "SELECT * FROM `dashboard_content`";
$check = strcmp("$token", "$dashboard_content_token");
$statement = mysqli_query($con, $sql);
if (check) {
$rows = mysqli_fetch_assoc($statement);
if (!$rows) {
echo "No results!";
} else {
while ($rows = mysqli_fetch_assoc($statement)) {
$news_id = $rows['news_id'];
$image_url = $rows['image_url'];
$news_title = $rows['news_title'];
$news_description = $rows['news_description'];
$news_article = $rows['news_article'];
$result['dashboard content: '][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
echo json_encode($result);
}
// do {
// $news_id = $rows['news_id'];
// $image_url = $rows['image_url'];
// $news_title = $rows['news_title'];
// $news_description = $rows['news_description'];
// $news_article = $rows['news_article'];
// $result['dashboard content: '][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
// echo json_encode($result);
// } while ($rows = mysqli_fetch_assoc($statement));
mysqli_free_result($statement);
}
}
?>
This should work. You'll want to use the do...while statement otherwise the first result is skipped.
<?php
$dashboard_content_token = $_REQUEST["dashboard_content_token"];
$token = "g4";
require(cc_scripts/connect.php);
$sql = "SELECT * FROM `dashboard_content`";
$check = strcmp("$token", "$dashboard_content_token");
$statement = mysqli_query($con, $sql);
if (check) {
$rows = mysqli_fetch_assoc($statement);
if (!$rows) {
echo "No results!";
} else {
do {
$news_id = $rows['news_id'];
$image_url = $rows['image_url'];
$news_title = $rows['news_title'];
$news_description = $rows['news_description'];
$news_article = $rows['news_article'];
$result['dashboard content: '][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
} while ($rows = mysqli_fetch_assoc($statement));
mysqli_free_result($statement);
echo json_encode($result);
}
}
?>
The key is to put all of you results into an array and then just do one json_encode(). When you call json_encode() multiple times, your API will return invalid json.
In your while loop,
$result['dashboard content: '] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
just over-writes the same "dashboard content" entry in the $result array every time you run the loop. This is why you only see the last entry.
Doing json_encode() within the loop makes no sense as well, because you'll just output multiple, disconnected individual JSON objects, which are not part of an array or coherent structure. This doesn't make for a valid JSON response.
It's not abundantly clear exactly what output structure you're hoping for, but this might give you either a solution, or at least a shove in the right direction:
$statement = mysqli_query($con, $sql);
$result = array("dashboard_content" => array()); //create an associative array with a property called "dashboard_content", which is an array. (json_encode will convert an associative array to a JSON object)
if (check) {
$rows = mysqli_fetch_assoc($statement);
if (!$rows) {
echo "No results!";
} else {
while ($rows = mysqli_fetch_assoc($statement)) {
$news_id = $rows['news_id'];
$image_url = $rows['image_url'];
$news_title = $rows['news_title'];
$news_description = $rows['news_description'];
$news_article = $rows['news_article'];
//append the current data to a new entry in the "dashboard_content" array
$result["dashboard_content"][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
}
}
//now, output the whole completed result to one single, coherent, valid JSON array.
echo json_encode($result);
You should end up with some JSON like this:
{
"dashboard_content": [
{
"news_id": 1,
"image_url": "abc",
"news_title": "xyz",
//...etc
},
{
"news_id": 2,
"image_url": "def",
"news_title": "pqr",
//...etc
},
//...etc
]
}

Change JSON format php

I have this php code that i need to change the JSON format i get the data from a mysql db:
// Retrieve data from database
$sql="SELECT nombre FROM deudores ORDER BY fecha ASC LIMIT 10";
$result=mysqli_query($con, $sql);
$emparray = array();
// Start looping rows in mysql database.
while($rows=mysqli_fetch_assoc($result)){
$emparray[] = $rows;
// close while loop
}
//print_r($emparray);
//echo json_encode($emparray);
$output = array(
'c2array' => true,
'size' => array(
0 => count($emparray),
1 => 1,
2 => 1
),
'data' => array()
);
$x = 0;
foreach ($emparray as $value) {
$output['data'][$x] = array();
$output['data'][$x][0] = array();
$output['data'][$x][0][0] = $value;
$x++;
}
echo json_encode($output);
That code print this JSON:
{"c2array":true,"size":[7,1,1],"data":[[[{"nombre":"test"}]],[[{"nombre":"Oscar"}]],[[{"nombre":"Oscar"}]],[[{"nombre":"test"}]],[[{"nombre":"test"}]],[[{"nombre":"oscar"}]],[[{"nombre":"Oscar"}]]]}
but i need the JSON to look like this:
{"c2array":true,"size":[7,1,1],"data":[[[test]],[[Oscar]],[[Oscar]],[[test]],[[test]],[[oscar]],[[Oscar]]]}
How can i achive this?
Thanks in advance!
Use mysql_fetch_row() instead of mysql_fetch_assoc.
while($rows=mysqli_fetch_row($result)){
$emparray[] = $rows;
// close while loop
}
And just set $emparray as value for $output['data']. No need extra work!
$output['data'] = $emparray;
This should make the output like this :
{"c2array":true,"size":[7,1,1],"data":[["test"],["Oscar"],["Oscar"],["test"],["test"],["oscar"],["Oscar"]]}

Get specific JSON data from sql query using PHP

I would like to say thank you for reading this question.
And my question is. I have this php code with sql query:
mysql_connect($mysql_server, $mysql_login, $mysql_password);
mysql_select_db($mysql_database);
$req = "SELECT name, elements "
."FROM lwzax_zoo_item "
."WHERE application_id = '2' AND elements LIKE '%".$_REQUEST['term']."%' ";
$query = mysql_query($req);
while($row = mysql_fetch_array($query))
{
$results[] = array('label' => $row['name'], 'desc' => $row['elements']);
}
$json = json_encode($results);
echo $json;
And output is:
[
{
"label":"0146T",
"desc":" {\n\t\"cec36dd6-ffde-494d-b25c-8e58bff84e22\": {\n\t\t\"0\": {\n\t\t\t\"value\": \"Ccta W\\/Wo Dye\"\n\t\t}\n\t}\n}"
},
{
"label":"64653",
"desc":" {\n\t\"cec36dd6-ffde-494d-b25c-8e58bff84e22\": {\n\t\t\"0\": {\n\t\t\t\"value\": \"Chemodenervation Eccrine Glands Oth Area Per Day\"\n\t\t}\n\t}\n}"
}
]
But I need only label data and value data...so it should look like:
[
{
"label":"0146T",
"desc":"Ccta W\\/Wo Dye"
},
{
"label":"64653",
"desc":"Chemodenervation Eccrine Glands Oth Area Per Day"
}
]
Could you please help me?
Thank you very much for help
UPDATE: Deleted $b = json_decode($row['desc'], true); as it wasn't used, just a junk from all my attempts to succeed.
You're decoding the JSON and assigning it to $b, but you're not doing anything with that variable. Use:
$results[] = array('label' => $row['name'],
'desc' => $b['cec36dd6-ffde-494d-b25c-8e58bff84e22'][0]['value']);
Also, you need to give a second argument to json_decode, so it will return an associative array rather than an object.
$b = json_decode($row['elements'], true);
OK, well, first things first, initialize your array OUTSIDE your loop.
while($row = mysql_fetch_array($query))
{
$b = json_decode($row['elements']);
$results[] = array('label' => $row['name'], 'desc' => $row['elements']);
}
Then you should probably do this:
$results = array();
while($row = mysql_fetch_array($query))
{
$b = json_decode($row['elements']);
array_push($results, array('label' => $row['name'], 'desc' => json_decode($row['elements'], true));
}
The at the end
$json = json_encode($results);
echo $json;
See if that helps.

Pulling data from MySQL into json array

I'm trying to pull data from my database using json in php. I have a few elements I need to specific then to post them on a page.
I want to "fetch" the data from mysql and return it to a json_encode. How can I do this using the SELECT method. Some had used PDO methods and other have used mysql_assoc, which confuses me.
For instance,
I have rows of: 'id' , 'title' , 'start', 'backgroundColor'...etc. along with a default value for all of them. ($array[] = "someValue = default")
I want it to export like so:
array(
'id' => 1,
'title' => "someTitle",
'start' => "2012-04-16",
'backgroundColor' => "blue",
'someValue' = > "default",
...
), ....
));
If anyone could help me with this with the best detail, I'd be awesome!
If you wanted to do this with PDO then here is an example:
<?php
$dbh = new PDO("mysql:host=localhost;dbname=DBNAME", $username, $password);
$sql = "SELECT `id`, `title`, `time`, `start`, `backgroundColor`
FROM my_table";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
//To output as-is json data result
//header('Content-type: application/json');
//echo json_encode($result);
//Or if you need to edit/manipulate the result before output
$return = [];
foreach ($result as $row) {
$return[] = [
'id' => $row['id'],
'title' => $row['title'],
'start' => $row['start'].' '.$row['time'],
'backgroundColor' => $row['backgroundColor']
];
}
$dbh = null;
header('Content-type: application/json');
echo json_encode($return);
?>
You don't "fetch to a json array".
You fetch your database results into a PHP array, then convert that php array, AFTER THE FETCHING IS COMPLETED, to a json string.
e.g.
$data = array();
while ($row = mysql_fetch_assoc($results)) {
$data[] = $row;
}
echo json_encode($data);
You can get the result from mysql,then format it to json
$array = array();
while($row = mysqli_fetch_array($result))
{
array_push($array,$row);
}
$json_array = json_encode($array);
Please check for SELECT methods here
In general it would look like this
$data = array(); // result variable
$i=0
$query = "SELECT id,title,start,backgroundColor FROM my_table"; // query with SELECT
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){ // iterate over results
$data['item'][$i]['id'] = $row['id']; // rest similarly
...
...
$i++;
}
header('Content-type: application/json'); // display result JSON format
echo json_encode(array(
'success' => true,
'data' => $data // this is your data variable
));

Categories