How to write JSON array in key:value format - php

I am trying to get a JSON array form PHP output which fetches multiple values from the database and converts to JSON array. The PHP code is as follows:
php
$result = $conn->query("SELECT dbname FROM users ORDER BY dbname ASC");
//defined second array for dbnames' list
$dblist = array();
while($row = $result->fetch_assoc()){
//array_push($response['dblist'],$row['dbname']);
$dblist = array('name'=>$row['dbname']);
}
$response['dblist'] = $dblist;
echo json_encode($response);
It gives the following output:
JSON
{"dblist":["a","arsod"]}
But, in order to extract values from JSON, the needed array is like:
json
{"dblist":{"name":"a","name":"arsod"}}
how can I achieve this? I want to fetch these values in android app.

Try this:
$result = $conn->query("SELECT dbname FROM users ORDER BY dbname ASC");
$dblist = [];
while($row = $result->fetch_assoc()){
$dblist[] = ['name'=>$row['dbname']];
}
$response['dblist'] = $dblist;
echo json_encode($reposne);
I basicaly added [] to $dbList so it looks like $dbList[] = ...
And with this, you will get a valid JSON that looks like this:
{"dblist":[{"name":"a"},{"name":"b"}]}
AS you requested output is not a good idea, since you will have duplicate keys in JSON

Your error is a common mistake and basically only effects this row:
$dblist = array('name'=>$row['dbname']);
where you set $dblist to a new created array in each iteration. What you want to do is adding a new entry to a list on every iteration
$entry = array('name'=>$row['dbname']);
array_push($dblist, $entry);
Which is the same, as
$entry[] = array('name'=>$row['dbname']);

Related

How to add resultset rows to a result array as indexed subarrays?

I have a mysqli resultset with two columns of data and several rows. I want to store each row of the resultset as an indexed subarray in my result array (specifically in $rows['data']).
This is my current code:
$query = mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while ($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Energy_UTC'];
$rows['data'][] = $tmp['Total_watts'];
}
This results in an array that looks like this:
{"name":"Total_watts","data":[1519334969,259,1519335149,246,1519335329,589,1519335509,589,1519335689,341,1519335869,341,1519336050,523,1519336230,662,1519336410,662,1519336590,469]}
But I need the result to be an array that looks like this:
{"name":"Total_watts","data":[1519334969,259],[1519335149,246],[1519335329,589],[1519335509,589],[1519335689,341],[1519335869,341],[1519336050,523],[1519336230,662],[1519336410,662],[1519336590,469]}
Can someone suggest a change in the PHP while loop to produce this output?
You just need to adjust your syntax to place the elements in the same subarray.
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = [$tmp['Energy_UTC'],$tmp['Total_watts']];
}
p.s. Additionally, you could use mysqli_fetch_assoc() since you are only accessing the associative keys. Or even better, use mysqli_fetch_row() and assign the row to your result array.
All baked, it could look like this:
if(!$result=mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings")){
// handle the query error
}else{
$rows=['name'=>'Total_watts'];
while($row=mysqli_fetch_row($result)){
$rows['data'][]=$row; // this will store subarrays like: [1519334969,259]
}
}

how to retrieve value only of JSON by php from database?

may I know how to retrieve the value only array in json instead of the whole json object in php from the database?
<?php
require_once('dbConnect.php');
$sql = "SELECT RestaurantName FROM Restaurant";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$restaurantArray = array();
while($rows = mysqli_fetch_assoc($result)) {
$restaurantArray[] = $rows;
}
echo json_encode($restaurantArray);
mysqli_close($connection);
?>
For example,
["Afonso Cláudio", "Água Doce do Norte"]
instead of
[{"city":"Afonso Cláudio"},{"city":"Água Doce do Norte"}]
When fetching data from the database as assoc, you will get an associative array (which when converted to json will become a json object) as result.
What you are currently doing is adding the row (which is an associative array with one key-value) to your result array. If you only want the city, you can easily fetch only that data from the assoc-array.
Changing
$restaurantArray[] = $rows;
to
$resturantArray[] = $rows['city'];
should do the trick.
Additionally, if you wanted to reformat the data in the result, and not just push the city name to it, a array_map call could be used:
$result = array_map(function($assocArr) {
return $assocArr['city']; // Or whatever you want the value to be.
},
$resturantArray);
echo json_encode($result);
How about you change this line:
$restaurantArray[] = $rows;
With:
$restaurantArray[] = $rows['city']; // (or 'RestaurantName')

Php append value to an exsisting array

Hi I need to add some value-key pair to an array which is the output of mysql query. Below is the code,
$query = "select TITLE,DESCRIPTION from TABLE where ID='1234'";
$result = mysqli_query($conn, $query);
$numrows = mysqli_num_rows($result);
if($numrows>0)
{
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$myArray[] = $row;
}
}
echo json_encode($myArray);
Giving me the result like
[{"TITLE":"Special","DESCRIPTION":"This is DESCRIPTION."}]
Now I need to to add an another key-value pair to generate the json output like,
[{"TITLE":"Special","DESCRIPTION":"This is DESCRIPTION.","URL":"imgname.jpg"}]
So I added the code
$myArray["URL"]="imgname.jpg";
echo json_encode($myArray);
But giving me the output like,
{"0":{"TITLE":"Chef Special","DESCRIPTION":"Grilled Salmon and crab."},"URL":"imgname.jpg"}
Is there anything wrong with above code.
check your data with
var_dump($myArray);
and you will find, that it is a 2-dimensional array. you'd have to add your data with
$myArray[0]["URL"] = "imgname.jpg";
If you have to add after encoding it, reverse with:
$a = json_decode($myArray,true)
add a new pair of key, value with $a['URL'] = "imgname.jpg" and then encode again.

Convert Selected row to JSON - PHP

I want to convert selected result into JSON.
Here is my code:
<?php
include("DbConnect.php");
$connection=new DbConnect();
$sth = mysqli_query($connection->_con,"SELECT * FROM account WHERE ac_id='1'");
if($sth){
$rows = array();
while($row = mysqli_fetch_assoc($sth)){
$users = mysqli_query($connection->_con,"SELECT user.user_id,user.name,user.email,ac_detail.ac_id,ac_detail.amount FROM user,ac_detail WHERE ac_detail.ac_id='1' AND user.user_id=ac_detail.user_id");
$usersArray = array();
while($userRow = mysqli_fetch_assoc($users)){
$usersArray[]=$userRow;
}
$a=array("users"=>$usersArray);
//$row["user"]=$usersArray
array_push($row,$a);
$rows[] = $row;
}
echo json_encode(array('data'=>$rows));
}else{
echo json_encode(array('message'=>'error - 2'));
}
?>
By executing this code it generate JSON like :
{"data":[{"ac_id":"1","user_id":"2","title":"Travel","ac_for":"Traveling","required_amount":"50","current_amount":"0","initial_date":"2014-11-11","final_date":"2014-11-14","is_shared":"1","status":"1","0":{"users":[{"user_id":"2","name":"Muhammad Imran","email":"macrotechnolgies#gmail.com","ac_id":"1","amount":"0"},{"user_id":"3","name":"Muhammad Imran","email":"macrotecholgies#gmail.com","ac_id":"1","amount":"0"}]}}]}
But i don't want "0"{"user::...}
How it should be (Expected Results) :
{"data":[{"ac_id":"1","user_id":"2","title":"Travel","ac_for":"Traveling","required_amount":"50","current_amount":"0","initial_date":"2014-11-11","final_date":"2014-11-14","is_shared":"1","status":"1","users":[{"user_id":"2","name":"Muhammad Imran","email":"macrotechnolgies#gmail.com","ac_id":"1","amount":"0"},{"user_id":"3","name":"Muhammad Imran","email":"macrotecholgies#gmail.com","ac_id":"1","amount":"0"}]}]}
Thanks in advance
You're doing:
while($row = mysqli_fetch_assoc($sth)){
[...snip...]
array_push($row,$a);
The while line creates an array $row, which you then use parts of to create $a. You then push that $a BACK onto the original $row array. But $row is an associative array already, so the pushed $a gets key 0.
Since you're now mixing an associative array (non-numeric keys) with a numeric-keyed array (the push operation), PHP MUST add the numeric key to your pushed item: You can't have an element in an array WITHOUT a key.
Then, since JS doesn't allow actual JS arrays ([]) to have non-numeric keys, the whole thing has to get converted into an object ({}).
What you probably want is something more like:
while($row = ...) {
... build $a ...
array_push($row['users'], $a);
instead.
Why don't you in stead array_push($row,$a) try following:
<?php
include("DbConnect.php");
$connection=new DbConnect();
$sth = mysqli_query($connection->_con,"SELECT * FROM account WHERE ac_id='1'");
if($sth){
$rows = array();
while($row = mysqli_fetch_assoc($sth)){
$users = mysqli_query($connection->_con,"SELECT user.user_id, user.name, user.email, ac_detail.ac_id, ac_detail.amount FROM user,ac_detail WHERE ac_detail.ac_id='1' AND user.user_id=ac_detail.user_id");
$usersArray = array();
while($userRow = mysqli_fetch_assoc($users)){
$usersArray[]=$userRow;
}
// here comes the change
// $a = array("users"=>$usersArray);
// //$row["user"]=$usersArray
// array_push($row,$a);
$row['users'] = $usersArray;
$rows[] = $row;
}
echo json_encode(array('data'=>$rows));
}else{
echo json_encode(array('message'=>'error - 2'));
}
This should work. Dont have sample data to test it.

Get rows from mysql table to php arrays

How can i get every row of a mysql table and put it in a php array? Do i need a multidimensional array for this? The purpose of all this is to display some points on a google map later on.
You need to get all the data that you want from the table. Something like this would work:
$SQLCommand = "SELECT someFieldName FROM yourTableName";
This line goes into your table and gets the data in 'someFieldName' from your table. You can add more field names where 'someFieldName' if you want to get more than one column.
$result = mysql_query($SQLCommand); // This line executes the MySQL query that you typed above
$yourArray = array(); // make a new array to hold all your data
$index = 0;
while($row = mysql_fetch_assoc($result)){ // loop to store the data in an associative array.
$yourArray[$index] = $row;
$index++;
}
The above loop goes through each row and stores it as an element in the new array you had made. Then you can do whatever you want with that info, like print it out to the screen:
echo $row[theRowYouWant][someFieldName];
So if $theRowYouWant is equal to 4, it would be the data(in this case, 'someFieldName') from the 5th row(remember, rows start at 0!).
$sql = "SELECT field1, field2, field3, .... FROM sometable";
$result = mysql_query($sql) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
echo $array[1]['field2']; // display field2 value from 2nd row of result set.
The other answers do work - however OP asked for all rows and if ALL fields are wanted as well it would much nicer to leave it generic instead of having to update the php when the database changes
$query="SELECT * FROM table_name";
Also to this point returning the data can be left generic too - I really like the JSON format as it will dynamically update, and can be easily extracted from any source.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo json_encode($row);
}
You can do it without a loop. Just use the fetch_all command
$sql = 'SELECT someFieldName FROM yourTableName';
$result = $db->query($sql);
$allRows = $result->fetch_all();
HERE IS YOUR CODE, USE IT. IT IS TESTED.
$select=" YOUR SQL QUERY GOOES HERE";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
THANKS

Categories