Convert Selected row to JSON - PHP - 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.

Related

How to write JSON array in key:value format

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']);

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.

Fetching data from Oracle database and store into an array using PHP

I'm trying to fetch data from database, date-with-time(timestamp) and values(number) , and storing into an array using php.
here is my data in database as follows=
WD DT
25-FEB-15 12.14.00.000000 AM 15.739993
25-FEB-15 12.23.00.000000 AM 13.698263
25-FEB-15 12.43.00.000000 AM 13.214383
fetch.php
<?php
include("md.php");
$sql = "SELECT * from datatable";
$result =oci_parse($conn, $sql);
$r=oci_execute($result);
$arr = array();
$row=oci_num_rows($stid);
$arr[0]=array('wd','dt');
for($i=1; $i<($row+1); $i++)
{
$arr[$i]= array(substr(oci_result($result, $i-1, "wd"),0,18),(float)oci_result($result,$i-1,"dt"));
//$arr[$i]= array(substr(oci_result($result, $i-1, "wd"),0,18),(int)oci_result($result,$i-1,"dt"));
}
echo json_encode($arr);
//print_r($arr);
?>
$arr getting following output:
[["WD"],["DT"]]
Q1. Why am i not getting rest of data? where am i doing wrong?
but if i use
while($row = oci_fetch_row($stid)){
$arr[] = $row;
}
if i use json_encode then =
[["25-FEB-15 12.14.00.000000 AM","15.739993"],["25-FEB-15 12.23.00.000000 AM","13.698263"],["25-FEB-15 12.43.00.000000 AM","13.214383"],....
if i use
while($row = oci_fetch_array($stid,OCI_ASSOC)){
$arr[] = $row;
}
if i use json_encode then =
[{"WD":"25-FEB-15 12.14.00.000000 AM","DT":"15.739993"},{"WD":"25-FEB-15 12.23.00.000000 AM","DT":"13.698263"},........]
I want the output as follows=
[["25-FEB-15 12.14.00 AM",15.739993],["25-FEB-15 12.23.00 AM",13.698263],["25-FEB-15 12.43.00 AM",13.214383],....]
Q2. How can i get it?
please help
Because the data is being returned in an associative array you get the column name and the data for each column in each row returned to you. So this is being returned in $row
"WD" => "25-FEB-15 12.14.00.000000 AM", "DT" => "15.739993"
All you need to do is pick out the data from each row and ignore the Key like so :-
$arr = array();
while($row = oci_fetch_array($stid,OCI_ASSOC)){
$arr[] = array($row['WD'] , $row['DT']);
}
echo json_encode($arr);

Add element and key to array php

I'm trying to add an element to array, but I get a weird output. The code is the following:
$getalltokens = $db->query("SELECT * FROM Tables WHERE available = '$comp'");
while ($row = $getalltokens->fetch(PDO::FETCH_ASSOC))
{
$fid = $row['FID'];
$tok = $row['token'];
$sql = $db->query("SELECT Firstname,Lastname FROM Users WHERE Token = '$tok'");
$rez = $sql->fetch(PDO::FETCH_ASSOC);
$names[] = $rez;
$fidzy = array(
'FID' => $fid
);
array_push($names, $fidzy);
}
$getalltokens = $db->query("SELECT FID FROM Tables WHERE available = '$comp'");
$tokenz = $getalltokens->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($names);
And the output I get is:
[{"Firstname":"Test","Lastname":"Test"},{"FID":"5"},
{"Firstname":"Test2","Lastname":"Test2"},{"FID":"4"}]
While what I need is the FID to be inside the $names array, so it would be more like:
[{"Firstname":"Test","Lastname":"Test","FID":"5"}]
$rez['FID'] = $fid; /* Added */
$names[] = $rez;
/* $fidzy and array_push removed */
You can use instead of array_push() like
$arrayname[indexname] = $value;
if you use array_push()
<?php
$array[] = $var;
?>
Note: If you use `array_push()` to add one element to the array it's
better to use$array[] = because in that way there is no overhead of
calling a function.
Note: `array_push()` will raise a warning if the first argument is not an array. This differs from the `$var[]` behavior where a new array
is created.
Reference Array push
The solution to the specific problem at hand is selecting all the necessary data in a single query, removing the need to add elements to any array. This is done in the following fashion:
$sql = $db->query("SELECT
Users.Firstname,Users.Lastname,Tables.FID
FROM Users,Tables
WHERE Users.Token = Tables.token");
$rez = $sql->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rez);

PHP Fatal error: Cannot use object of type stdClass as array

I need a help on below, I know its raised in a past but I am currently struggling to figure it out the error Cannot use object of type stdClass as array on line
$score[$counter] = ($bronze * $tempArray[6]) + ($silver * $tempArray[5]) + ($silver * $tempArray[4]);
Code:
<?php
//turning the date other way around that is why explode the date string and stored in an Array
$gold=$_GET['gold_input'];
$silver=$_GET['silver_input'];
$bronze=$_GET['bronze_input'];
$gdp_value=$_GET['gdp_checked'];
$link = new mysqli('localhost', 'root', '','coa123cdb');
$myArray = array();
//data format for information
//[{"name":"Ahmet Akdilek","country_name":"Turkey","gdp":"773091000000","population":"72752000"}
$query = "SELECT * FROM coa123cdb.Country";
$result = mysqli_query($link, $query)
or die("Error: ".mysqli_error($link));
$row_cnt = $result->num_rows;
if ($result = $link->query($query)) {
$tempArray = array();
$scorex=array($row_cnt);
$score=(object)$scorex;
$counter=0 ;
//while($row = $result->fetch_object()) {
while($row=mysqli_fetch_object($result)){
$tempArray = $row;
if($gdp_value==0)
{
$score[$counter]=($bronze*$tempArray[6])+($silver*$tempArray[5])+($silver*$tempArray[4]);
}
else
{$score[$counter]=($bronze*$tempArray[6]+$silver*$tempArray[5]+$silver*$tempArray[4])*$tempArray[1]/$tempArray[2]/10000;
}
array_push($tempArray, $score[$counter]);
array_push($myArray, $tempArray);
$counter=$counter+1;
}
//var_dump($score);
echo json_encode($myArray);
}
$result->close();
$link->close();
?>
mysqli_fetch_object returns an object.
So after the line $row=mysqli_fetch_object($result) is an object.
If you want an array use mysqli_fetch_array instead.
And before using that array check its contents with var_dump($row); (to prevent further questions).
Take a look at how you declared $score.
First you do $scorex=array($row_cnt); and then $score=(object)$scorex;.
So $score is cast to an object. However, in your code, you are still addressing it like an array, i.e. $score[$counter]. You should reference it as an object.
EDIT
Alternatively, update your definition for $score to the following:
$score = array_fill (0, $row_cnt, 0);
This way, your assignment to $score[$counter] will still work (i think in the way you intended).

Categories