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"]]}
Related
I'm trying to convert the result array from Mysql to JSON format, the format doesn't seems to be correct, a comma is missing between each object. Please advice, thank you.
I'm aware that im using the deprecated version of php here.
$result = mysql_query("SELECT * FROM patientvaccinedetail")or
die(mysql_error());
while($row = mysql_fetch_array( $result,MYSQL_ASSOC)) {
$specific = ["message" => $row["message"],
"mobile" => $row["mobile"]];
print_r (json_encode($specific));
}
Current Result:
{"message":"hello","mobile":"12345678"}{"message":"hi","mobile":"87878965"}
Desired Result:
{"message":"hello","mobile":"12345678"}, {"message":"hi","mobile":"87878965"}
You have to use array and at end of loop you have to echo result
$specific = array();
while($row = mysql_fetch_array( $result,MYSQL_ASSOC)) {
$specific[] = ["message" => $row["message"],
"mobile" => $row["mobile"]];
}
echo json_encode($specific);
Please moved json_encode() to outside of while loop.
$specific = array();
while($row = mysql_fetch_array( $result,MYSQL_ASSOC)) {
$specific = ["message" => $row["message"],
"mobile" => $row["mobile"]];
}
print_r(json_encode($specific));
I need to display multiple data row and display json data. Here is my code:
<?php
$dinner_food_category=$_GET['DinnerFoodCategory'];
$conn = mysqli_connect("localhost","taig9_gen_user","GenAdmin1/Pass");
if($conn) {
$select_database = mysqli_select_db($conn,"taig9_genumy");
$select_query = "SELECT food_id,food_name,serving_type,serving_type_amount,singal_unit_weight FROM food_details WHERE category_id IN ('VEG00','VGB00','SUP00','CAK00')";
$result = mysqli_query($conn, $select_query);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$foods_id=$row['food_id'];
$foods_name=$row['food_name'];
$foods_type=$row['serving_type'];
$foods_type_amount=$row['serving_type_amount'];
$singal_unit_weights=$row['singal_unit_weight'];
}
$data = array("FoodId" => $foods_id,"FoodNames" => $foods_name,"FoodType" => $foods_type,"FoodAmount" => $foods_type_amount,"SingalUnitWeight"=> $singal_unit_weights);
}
echo stripslashes(json_encode($data));
}
?>
On each iteration of while you food_ variables are overwritten, and after while loop is over - you have value for the last row only. To avoid this you should add variables to $data inside a while loop with [] notation:
while ($row = mysqli_fetch_assoc($result)) {
$data[] = array(
"FoodId" => $row['food_id'];
"FoodNames" => $row['food_name'];
"FoodType" => $row['serving_type'];
"FoodAmount" => $row['serving_type_amount'];
"SingalUnitWeight" => $row['singal_unit_weight'];
);
}
// using `stripslashes` is useless
echo json_encode($data);
if (mysqli_num_rows($result) > 0) {
$data = [];
foreach ($result as $row) {
$foods_id=$row['food_id'];
$foods_name=$row['food_name'];
$foods_type=$row['serving_type'];
$foods_type_amount=$row['serving_type_amount'];
$singal_unit_weights=$row['singal_unit_weight'];
$data[] = ["FoodId" => $foods_id,"FoodNames" => $foods_name,"FoodType" => $foods_type,"FoodAmount" => $foods_type_amount,"SingalUnitWeight"=> $singal_unit_weights];
}
echo stripslashes(json_encode($data));
}
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.
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
));
This is my code
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT title,text,date FROM news limit 5");
is there any way to extract title,text,date from $result and put them into 3 dimensional array?
What about
$result = mysql_query("SELECT title,text,date FROM news limit 5");
$array = array();
$i = 0;
while( $row = mysql_fetch_assoc( $result ) {
$array[$i] = array();
// i'm just guessing at what sort of array you want
$array[$i][$row['title'] = array( 'text' => $row['text'], 'date' => $row['date'] );
$i++;
}
I'd be interested to know what the ... you need a three-dimensional array for but ok:
$dim = array();
$result = mysql_query(...);
while ( $row = mysql_fetch_assoc($result) )
// Whatever you want to save in that particular bucket,
// I'll be using the result set
$dim[$row['title']][$row['text']][$row['date']] = $row;
Strange, ...
If we are already guessing, here is mine:
$results = array();
while(($row = mysql_fetch_assoc($result))) {
$results[] = $row;
}
which will create an array like this:
array(array('title' => 'foo',
'text' => 'bar',
'date' => 'baz'),
//...
)
I think what you're after is actually a two-dimensional array (in which the second dimension has three elements). (Correct me if I'm wrong.)
One of the comments under the documentation of mysql_fetch_array has an answer to this:
(Disclamer: This code is unnecessarily verbose. I prefer not changing it though as I have copied it from the above web-page. For improvements, I refer to the comments.)
<?php
function mysql_fetch_rowsarr($result, $numass=MYSQL_BOTH) {
$i=0;
$keys=array_keys(mysql_fetch_array($result, $numass));
mysql_data_seek($result, 0);
while ($row = mysql_fetch_array($result, $numass)) {
foreach ($keys as $speckey) {
$got[$i][$speckey]=$row[$speckey];
}
$i++;
}
return $got;
}
?>
You should then be able to use this function as
<?
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT title,text,date FROM news limit 5");
$arr = mysql_fetch_rowsarr($result);
$row_2_title = $arr[2]['title'];
?>