Put json array inside json object in PHP - php

Hello Stackoverflow community, i'm little bit confused how i can achieve this. So this is how my json response should look:
some_array: [
{
some_json_object_atribute_1:
some_json_object_atribute_2:
// Here i need an array
json_array: [
]
}
{
some_json_object_atribute_1:
some_json_object_atribute_2:
}
]
But i'm only getting one row from json array. This is some part of the code:
$response["chat_rooms"] = array();
while ($chat_room = $result->fetch_assoc()) {
$tmp = array();
$tmp["chat_room_id"] = $chat_room["chat_room_id"];
$unread_messages = $db->getAllUnreadMsgsFromChatRoom($user_id, $chat_room["chat_room_id"]);
while ($unread_message = $unread_messages->fetch_assoc()) {
// Here i need one json array
$tmp["message_id"] = $unread_message["message_id"];
}
array_push($response["chat_rooms"], $tmp);
}

You are overriding $tmp["chat_room_id"] in every run of the while loop.
The right syntax would be:
$tmp["chat_room_id"][] = $unread_message["message_id"];
or
array_push($tmp["chat_room_id"], $unread_message["message_id"]);

Related

Append php loop data to JSON object

I need looped php data in an html template so I know it has something to do with JSON however not a JSON expert and cannot find much help in searching the web.
$uniqueFranchise_id = array_unique($franchise_id);
$dataArr = '[
{
"name": "Dylan",
"page_link": "https://mypage.com/"
}
]';
foreach($uniqueFranchise_id as $franchise)
{
$sqlFranchise = "select * from franchise where franchise_id = $franchise";
$resultFranchise = $conn->query($sqlFranchise);
if($resultFranchise->num_rows > 0)
{
while($rowFranchise = $resultFranchise->fetch_assoc())
{
$dataArr = json_decode($data, TRUE);
$dataArr[] = "['name'=>'".$rowFranchise['name']."', 'page_link'=>'".$rowFranchise['page_link']."']";
//$json = json_encode($dataArr);
}
}
}
$json = json_encode($dataArr);
print_r($dataArr);
But it only appends one row. In fact it deleteds that data that's already in my dataArr and just adds one row from my loop? Maybe I'm approaching this situation completely wrong?
You set your $dataArr inside the while-loop. So each time the loop is runs, it will be overwritten. Also, it makes more sense and it's much more clear when you handle it as an array (or object) and afterwards convert it to JSON.
$dataArr = array(array('name' => 'Dylan', 'page_link' => 'https://mypage.com/'));
foreach($uniqueFranchise_id as $franchise)
{
$sqlFranchise = "select * from franchise where franchise_id = $franchise";
$resultFranchise = $conn->query($sqlFranchise);
if($resultFranchise->num_rows > 0)
{
while($rowFranchise = $resultFranchise->fetch_assoc())
{
$dataArr[] = array('name' => $rowFranchise['name'], 'page_link' => $rowFranchise['page_link']);
}
}
}
$json = json_encode($dataArr);
echo $json;
You shouldn't be building the string up by yourself, you should build the data and then JSON encode the result (comments in code)...
$dataArr = '[
{
"name": "Dylan",
"page_link": "https://mypage.com/"
}
]';
// decode existing JSON to start array
$dataArr = json_decode($data, TRUE);
foreach($uniqueFranchise_id as $franchise)
{
// Read just the data you need from the table
$sqlFranchise = "select name, page_link from franchise where franchise_id = $franchise";
$resultFranchise = $conn->query($sqlFranchise);
if($resultFranchise->num_rows > 0)
{
// Read all of the rows into an array
$newData = $resultFranchise->fetch_all(MYSQLI_ASSOC);
// Add in existing data
$dataArr = array_merge($dataArr, $newData);
}
}
// Now encode the list of elements into 1 string
echo json_encode($dataArr);
You should also look into prepared statements if this data is not trusted to stop SQL injection.

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 parse json when it give different type of response

I am parsing data from JSON in Android, but JSON response is behaving strangely.
If it contains more than one data the response is like this
{"e":"701",
"data":[{"id":"121"},
{"id":"122"}
]
}
If it contains only one data the response is like this
{"e":"701",
"data":{"1":{"id":"93"}}
}
The code that send JSON response is
$r1=mysql_query($sql1,$con);
$count1=mysql_num_rows($r1);
if($count1>0)
{
while ($row1 = mysql_fetch_assoc($r1)) {
$data1[$i] = $row1 ;
}
}
$c = new Emp();
$c->e = "801";
$c->data =$data1;
echo json_encode($c);
How to parse this in one stretch? Any help would be appreciated.
How about you add this in the while loop ($e will be a variable which in the case above contains 801)
$info = array('e' => $e,
'data' => $data1
);
$rows[] = $info;
and then out of the while loop you take it out with json as an array which will give you the result you need if I get the question right.
echo str_replace("\\","", json_encode($rows));

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.

Having problems with getting arrays into arrays for json-encode

heres the function:
http://pastebin.com/tQLjzzbH
I want it to return this:
{"years":[
{
"yName":"2011",
"yAlbums:[
{
auID:"1234",
aID:"456",
etc..
},
{
auID:"12345",
aID:"4567",
etc..
}
},
{
"yName":"2010",
"yAlbums:[
{
auID:"2234",
aID:"556",
etc..
}
}
]}
but its only returning this:
{"years":[
{"yName":"2011"},
{"yName":"2010"}]}
Been trying to get this for ages, am totally lost now. Some help would be appreciated.
Thanks.
You have read your result to the very end by
while($data2 = mysql_fetch_assoc($result))
{
$yearsArrayRaw[] = $data2['album_year'];
}
Add mysql_data_seek($result,0) before inner while, to line 36. Also, I would suggest rewriting this function to have single loop, using something like
$year_albums= array();
while ($data = mysql_fetch_assoc($result)){
if (empty($years[$data['album_year']])){
$year_albums[$data['album_year'] = array(
'yName'=>$data['album_year'],
'yAlbums'=>array()
);
}
//...album creation logic here...//
$year_albums[$data['album_year']['yAlbums'][] = $album;
}
//Converting arrays into objects
$years = array();
foreach ($year_albums as $year){
$years[] = (object)$year;
}
json_encode($years);

Categories