I am having an issue with how I am converting my php array into a JSON object. No matter what I try, I either print everything out as multiple objects or it comes out as null.Wrapping it in pre tags, here is the closest that I got it:
My code:
$content = mysqli_query($dbcon,
"SELECT title, last_name AS lastname
FROM revision, field_last_name
WHERE vid = entity_id;"
);
echo "<pre>";
while($row = mysqli_fetch_array($content))
{
print json_encode($row);
print '<br/>';
}
echo "</pre>";
My output:
{"0":"John Apple","title":"John Apple","1":"Apple","lastname":"Apple"}
{"0":"Kumar Patel","title":"Kumar Patel","1":"Patel","lastname":"Patel"}
{"0":"Michaela Quinn","title":"Michaela Quinn","1":"Quinn","lastname":"Quinn"}
{"0":"Peyton Manning","title":"Peyton Manning, MD","1":"Manning","lastname":"Manning"}
{"0":"John Doe","title":"John Doe","1":"Doe","lastname":"Doe"}
{"0":"Jane Lee","title":"Jane Lee","1":"Lee","lastname":"Lee"}
{"0":"Dan McMan","title":"Dan McMan","1":"McMan","lastname":"McMan"}
{"0":"Yu Win","title":"Yu Win","1":"Win","lastname":"Win"}
My two questions are:
1) Why is there a "0":"John Apple" and a "1":"Apple" when all I want is "title":"John Apple" and "lastname":"Apple" in my object?
2) Why is everything displaying as multiple objects?
Thanks!
---EDIT---
$arr = array()
echo "<pre>";
while($row = mysqli_fetch_assoc($content))
{
$arr[] = $row;
}
print $arr;
echo "</pre>";
field_last_name is your table name? can you distinguish each column name prefix by table name like revision.title in your query and get all data in a single array and then json_encode it?
$content = mysqli_query($dbcon,
"SELECT title, last_name AS lastname
FROM revision, field_last_name
WHERE vid = entity_id;"
);
$arr = array();
echo "<pre>";
while($row = mysqli_fetch_assoc($content))
{
$arr[] = $row;
}
print_r(json_encode($arr));
echo "</pre>";
Change this:
while($row = mysqli_fetch_array($content))
{
print json_encode($row);
print '<br/>';
}
To this:
$row = mysqli_fetch_assoc($content);
json_encode($row);
...because you're printing out multiple objects. If you want a single object which is an array, you need to append the results of mysql_fetch_assoc (see other answer covering field names vs positions) to an array, then json_encode the array in one shot. Example:
$myarray = array();
while($row = mysqli_fetch_assoc($content))
{
$myarray[] = $row;
print '<br/>';
}
print json_encode($myarray);
Related
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.
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.
Right now I'm working on a new homepage for a museum, and I have to use the old database (because it has over 70k entries).
My job now is to change the values in the "dias" table (supporter row) from full names of the supporters to their IDs (supporter table).
Right know I'm using this code:
$result = mysql_query("SELECT pate FROM dias");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$pate = explode(" ", print_r($row[0]));
echo "<br>";
}
If I now put in $pate[0], I only get "1" as output (along with the names from the print_r).
My question is:
How can I split the names and save them seperately in a variable, because I think I need this to be able to compare the names with the one in the supporter table and to write the ids in the supporter row in the "dias" table.
If you need more infomration, feel free to ask.
explode needs a string as the second argument, but you are taking the return value of print_r, which is true in this case. Just take $row[0] and you should have an array of your data in $pate.
Try printing $pate after that.
$result = mysql_query("SELECT pate FROM dias");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$pate = explode(" ", $row[0]);
print_r($pate)
echo "<br>";
}
After that continue :).
It looks like you are talking about List() function. list() will enable you explode into variables like;
$address ="Benson Bush|4545547 | living in California" ;
list($name ,$code , $description) = explode("|", $address);
echo $name."<br>";
echo $code."<br>";
echo $description."<br>";
$result = mysql_query("SELECT pate FROM dias");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$pate = explode(" ", $row[0]);
print_r($pate);
echo "<br>";
}
Don't do this after you've received the data - do it from your query by using SUBSTRING_INDEX:
SELECT SUBSTRING_INDEX(pate, ' ', 1) FROM dias
$result = mysql_query("SELECT pate FROM dias");
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
print_r($data);
echo "</br>";
}
print_r($data);
If you would like to stored value in variable then you can use extract function also.
I am trying to print json_encode and I get output duplicated. I am certain there is one single record in database and yet it shows the same record data twice in various format. This is it:
[{"0":"Polo","name":"Polo","1":"City ","location":"City ","2":"Manama","city":"Manama"}]
The code behind this is:
$dataArray = array();
while($r = mysql_fetch_array($result))
{
$dataArray[] = $r;
}
print json_encode($dataArray, JSON_UNESCAPED_UNICODE);
Any idea?
This is because the default behavior of mysql_fetch_array() is to return both a column name and index keyed array.
Use mysql_fetch_assoc() or set the second parameter of mysql_fetch_array().
while($r = mysql_fetch_assoc($result)) {
$dataArray[] = $r;
}
You should set another fetch style. It now fetches all columns using both their 0 based index and their name.
This should work as expected:
$dataArray = array();
while($r = mysql_fetch_array($result, MYSQL_ASSOC))
{
$dataArray[] = $r;
}
print json_encode($dataArray, JSON_UNESCAPED_UNICODE);
You're getting this because you can access the results either by name or by column index, but you're serializing the entire thing, so both ways of getting the data are showing up.
try this
//$dataArray = array();
while($r = mysql_fetch_array($result))
{
$dataArray[] = $r;
}
print json_encode($dataArray, JSON_UNESCAPED_UNICODE);
I commented first line. Because you used like that $dataArray[].
I have the following:
while($myRow = odbc_fetch_array( $result )){ <--lots of rows
$thisResult['name'] = $myRow["name"] ;
$thisResult['race'] = $myRow["race"] ;
$thisResult['sex'] = $myRow["sex"];
$thisResult['dob'] = $myRow["dob"];
}
I can't figure out how to print this back out.
I want to get each row and iterate through each row in the array like a datareader. I'm not sure what to do. I do not want to do the echo in the while. I need to be able to print it out elsewhere. But I don't think I've done it right here to be able to print it later.
I also tried, this, however:
while($myRow = odbc_fetch_array( $result )){ <--lots of rows
print($thisResult[$myRow["name"]] = $myRow);
}
I then tried:
while($myRow = odbc_fetch_array( $result )){ <--lots of rows
print (odbc_result($myRow,"name"));
}
but got an error.
Thank you for any help.
EDIT: when I do this:
while($myRow = odbc_fetch_array( $result )){
print ($myRow["name"]);
}
I get undefined index name. I am mainly concerned with saving to an array but I have to be able to do it in the loop first.
Declare an array before and assign the values to it:
$rows = array();
while($myRow = odbc_fetch_array( $result )){ <--lots of rows
$rows[] = $myRow;
}
Then you can print it e.g. this way:
foreach($rows as $row) {
foreach($row as $key => $value) {
echo $key . ': '. $value;
}
}
or however you want to.
You don't have to access and assign $thisResult['name'] = $myRow["name"] in your while loop as $myRow already is an array. You just copy the values which is unnecessary.
You say you have a lot of rows. Depending of what you really want to do with data, it might be better to put all this functionality into the while loop to avoid creating an array.
How about something like:
$output = '';
while($myRow = odbc_fetch_array( $result )) {
$output = $output."Your name is {$myRow["name"]} and your race is {$myRow["race"]}\n";
}
// print output later...