Concatenate JSON in php with read Database - php

I read user from the database but I return json to ajax only return the last user because I cant concatenate the json encode.
$myObj = new \stdClass();
while ($fila = $bd->fila()) {
$myObj->NOMBRE = $fila["NOMBRE"];
$myObj->ROLENAME = $fila["ROLENAME"];
$myObj->IDUSER = $fila["IDUSER"];
$myJSON = json_encode($myObj);
}
echo $myJSON;

You are now overwriting $myJson in each iteration. We can also not "concatanate" two jsons (well, we could, but we shouldn't, cause it's laborious..).
Better put everything in one array/object and json_encode() at the very end.
$myObj = new \stdClass();
$users = array(); // instantiate a new array
while ($fila = $bd->fila()) {
$myObj->NOMBRE = $fila["NOMBRE"];
$myObj->ROLENAME = $fila["ROLENAME"];
$myObj->IDUSER = $fila["IDUSER"];
// add objects to that array
$users[] = $myObj;
}
// then at the end encode the whole thing to json:
echo json_encode($users);
Now here are some variants:
If you want everything that your db is returning in this items you could shorten that to:
$users = array(); // instantiate a new array
while ($fila = $bd->fila()) {
// add the whole item (cast as Object) to that array
$users[] = (Object) $fila;
}
// then at the end encode the whole thing to json:
echo json_encode($users);
If you don't care if the items are objects or arrays you could skip the casting and just add the array to the big array:
$users[] = $fila;

Maybe if you concatenate it as array like this
$myJSON[] = $myObj;
and then after the while
echo json_encode($myJSON);

You just have to collect data to big array and then encode whole array. Also there's no reason for creating new StdObjects instead of usual arrays.
// define empty array
$result = [];
while ($fila = $bd->fila()) {
// add to the array all needed elements one by one
$result[] = [
'NOMBRE' => $fila["NOMBRE"],
'ROLENAME' => $fila["ROLENAME"],
'IDUSER' => $fila["IDUSER"],
];
}
// encode whole result
echo json_encode($result);

Related

How I coul get a JSON like this?

I need to get a JSON with arrays, how I could do it?
//JSON I need to get
{"keywords":[{"keyword":"kw1", "tags":["sample"]},{"keyword":"kw2", "tags":["sample, sample2"]}]}
//For now, I got this
$keywords = array("kw1", "kw2");
$tags= array("sample", "sample2");
function Keywords($keywords, $tags){
$fields= array("keywords" => $keywords);
$jsondata = json_encode($fields);
print_r($jsondata );
}
//output
{"keywords":["kw1","kw2"]}
I expect the output like this:
{"keywords":[{"keyword":"kw1", "tags":["sample"]},{"keyword":"kw2", "tags":["sample, sample2"]}]}
Assuming tags in the first element of your example is supposed to be ["sample, sample2"] as well (otherwise you would really have to explain by what logic you want to achieve at the result as shown) …
$keywords = array("kw1", "kw2");
$tags= array("sample", "sample2");
$result = new StdClass;
$result->keywords = [];
foreach($keywords as $keyword) {
$temp = new StdClass;
$temp->keyword = $keyword;
$temp->tags = [];
foreach($tags as $tag) {
$temp->tags[] = $tag;
}
$result->keywords[] = $temp;
}
echo json_encode($result);
Basically two nested loops over the keywords and the tags, and inside a new temporary object is created an then appended to the result array.

how can produce json array with while in php

i want return my data from mysql to json array with do while loop.
when i return one record with json it is well. but i want return list of array in one json array.
how can do that with index in while? my code have error and i don't know how can do it. with one record it is well but more can't.
$json="array(";
do{
$json=."'$row_query['id']'=>array('fname'=>$row_query['fname'],'lname'=>$row_query['lname']),";
} while ($row_query = mysqli_fetch_assoc($query));
json=.")";
echo json_encode($json,JSON_UNESCAPED_UNICODE);
There's no need to add quotes, brackets, parentheses or whatever. json_encode function will do it for you. Just provide an array to it:
$json = [];
while ($row_query = mysqli_fetch_assoc($query)) {
$json[$row_query['id']] = [
'fname'=>$row_query['fname'],
'lname'=>$row_query['lname'],
];
}
echo json_encode($json,JSON_UNESCAPED_UNICODE);
This is the most super easy version. You may try this.
$json = new array();
do{
array_push($json,$row_query);
} while ($row_query = mysqli_fetch_assoc($query));
or
$json = [];
do{
$json[] = $row_query;
} while ($row_query = mysqli_fetch_assoc($query));
Atlast encode your json variable.
$json = json_encode($json);
echo $json;

how to add extra element to array with array_push in PHP?

I am developing in PHP/MS SQL for getting JSON Response.
Code which I wrote is:
while( $result = sqlsrv_fetch_object($sql_Gpo_Carr)) {
$array_res[] = $result; // add result to array
array_push($array_res, array('unidad' => $uni)); // add extra element
$jsonObj = json_encode($array_res); // encode JSON
}
echo $jsonObj;
exit();
This is what I want in result:
[{"idperiodo":"37","idgrupo":"1963","idhorario":"12832","unidades":null,"unidad":1}]
but the result shows me this:
[{"idperiodo":"37","idgrupo":"1963","idhorario":"12832","unidades":null},{"unidad":1}]
You're fetching an object. Add $uni to $result first and then add to $array_res:
while( $result = sqlsrv_fetch_object($sql_Gpo_Carr)) {
$result->unidad = $uni;
$array_res[] = $result;
}
Also, you probably want the json_encode() after the loop not in the loop:
echo json_encode($array_res);

Formatting json object using php

I'm trying to encode a json response using php, and having some trouble formatting it for use with ajax.
I'm basically trying to return an array of Rental objects, which each will include data for book, student, and teacher. Currently I'm using php to build objects like this...
while ($row = $result->fetch_array(MYSQLI_BOTH)) {
$obj = array();
// Build a book out of the results array, then push to the current object
$book = new Book();
$book->id = $row['book_id'];
$book->title = $row['title'];
$book->author = $row['author'];
$book->ar_quiz = $row['ar_quiz'];
$book->ar_quiz_pts = $row['ar_quiz_pts'];
$book->book_level = $row['book_level'];
$book->type = $row['type'];
$book->teacher_id = $row['teacher_id'];
array_push($obj, array('book' => $book));
// Build a student out of the results array, then push it to the current objects
$student = new Student();
$student->id = $row['student_id'];
$student->username = $row['student_username'];
$student->nicename = $row['student_nicename'];
$student->classroom_number = $row['classroom_number'];
array_push($obj, array('student' => $student));
// Build a teacher out of the results, push to current object
$teacher = new Teacher();
$teacher->id = $row['teacher_id'];
$teacher->username = $row['teacher_username'];
$teacher->nicename = $row['teacher_nicename'];
array_push($obj, array('teacher' => $teacher));
array_push($rentals, $obj);
}
mysqli_stmt_close($stmt);
return json_encode($rentals);
... building an $obj for each result, and then appending the whole $obj object to the end of $rentals, which is what I pass back in the end. Here is what the response looks like when I encode it to json:
[
[
{
"book":{
"id":113,
"title":"Book Test",
"author":"Test Test Author",
"ar_quiz":1,
"ar_quiz_pts":"10.0",
"book_level":"20.0",
"type":"Fiction",
"teacher_id":1
}
},
{
"student":{
"id":2,
"username":"studentnametest",
"classroom_number":2,
"nicename":"Student Name"
}
},
],
...
]
The problem here is that there is an extra {} around each of the book, student, and teacher objects, causing an extra step when trying to access in the javascript. For example, I think I have to use data[0].[0].book.title, when I really just want to be able to use data[0].book.title. How do I better structure this to fit my needs?
Don't add the additional array structure and you can simply change your array_push lines from
array_push($obj, array('book' => $book));
to
$obj['book'] = $book;

Retrieve all values in my loop and format it to json

I'm trying to build a page which queries my database and then formats output so another webservice/page can access the data.
Ideally I wanted to explore having the data in JSON format, but that is not working. The other problem I have which is more major than the JSON not working is, if I have 3 records in $reportsResult, only the last one is displayed.
Anyone with some help please. Oh do I also need to print_r for the external webpage to retrieve the data or is there a better way?
class Pupil {
public $FirstName = "";
public $LastName = "";
}
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil = new Pupil();
$Pupil->FirstName = $reportRecord->getField('FName');
$Pupil->LastName = $reportRecord->getField('SName');
}
json_encode($Pupil);
OK managed to figure out how how to get all records from the loop, but its still not displaying in json format when I do a print_r - am I missing something?
$AllPupils = array();
foreach($reportsResult->getRecords() as $reportRecord)
{
$Pupil = new Pupil();
$Pupil->FamID = $reportRecord->getField('FName');
$Pupil->ChildName = $reportRecord->getField('SName');
array_push($AllPupils, $Pupil);
}
json_encode($AllPupils);
Everytime your foreach loop starts again, it will override your $Pupil variable.
Try an array instead:
$Pupil = array()
$i = 0;
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil[$i] = new Pupil();
$Pupil[$i]->FirstName = $reportRecord->getField('FName');
$Pupil[$i]->LastName = $reportRecord->getField('SName');
$i++;
}
echo json_encode($Pupil);
Edit: mikemackintosh's solution should also work and could be a little bit faster (depending on the size of your foreach loop).
To display the results you need to echo your data (not only json_encode).
You will probably run into issues since json_encode wont handle the whole object. for that, you may want to serialize the $Pupil object.
Something like below may work for you though. It will assign the values to a returned array, which will allow json_encode to execute gracefully:
class Pupil {
public $FirstName = "";
public $LastName = "";
public function getAttr(){
return array("FirstName" => $this->FirstName, "LastName" => $this->LastName);
}
}
$json = array();
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil = new Pupil();
$Pupil->FirstName = $reportRecord->getField('FName');
$Pupil->LastName = $reportRecord->getField('SName');
$json[] = $Pupil->getAttr();
}
echo json_encode($json);
I am not sure why you have that class defined, but you know what in your for each have something like
foreach ($reportsResult->getRecords() as $key => $record) {
$data[$key]['firstname'] = $record->getField('Fname');
$data[$key]['lastname'] = $record->getField('Sname');
}
And then you can check the final array using print_r
and while output you can simply do a print json_encode($data) and it will give you a json string of all the items in the data array.
In php (at least), json_encode takes an array as parameter.
Therefore you should add a constructor to your class
function __construct($first, $last)
{
this.$FirstName = $first;
this.$LastName = $last;
}
and one for getting the full name as an array, ready to be jsoned
function getNameArray()
{
$nameArray = array();
$nameArray['firstName'] = this.$FirstName;
$nameArray['lastName'] = this.$LastName;
return $nameArray;
}
then in that foreach you build another array with all the pupils
$pupils = array();
foreach (bla bla)
{
$first = $reportRecord->getField('FName');
$last = $reportRecord->getField('SName');
$Pupil = new Pupil($first, $last);
array_push($pupils, $pupil.getNameArray());
}
finally, you have everything preped up
json_encode($pupils);
I'm sure there's other ways to debug your stuff, I use print_r mainly also.

Categories