I am trying to build a JSON response from my server side, but it is not working as expected.
It is probably something simple but, I am not so good at PHP...
The basic expected response is a JSON with a single JsonArray and some other fields, for that, the relevant piece of code is shown here:
Sample of expected JSON response:
{
"pageNr": 2
"totalPages":28
"products":[
{
"user_name":"testUser001",
"product_ID":"4756373abdhg"
},
{
"user_name":"testUser002",
"product_ID":"475ggdfghghg"
},
{
"user_name":"testUser003",
"product_ID":"47466gdgbdhg"
},
{
"user_name":"testUser004",
"product_ID":"4000nfaergeb"
},
{
"user_name":"testUser005",
"product_ID":"adfer73abdhg"
}
]
}
Basic PHP code used to generate desired JSON (among sql query and other things):
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response = ['pageNr' => $page];
$response = ['totalPages' => $totalPages];
$response = ['products' => $res2];
Response that this code is generating on Postman:
{
"products":[
{
"user_name":"testUser001",
"product_ID":"4756373abdhg"
},
{
"user_name":"testUser002",
"product_ID":"475ggdfghghg"
},
{
"user_name":"testUser003",
"product_ID":"47466gdgbdhg"
},
{
"user_name":"testUser004",
"product_ID":"4000nfaergeb"
},
{
"user_name":"testUser005",
"product_ID":"adfer73abdhg"
}
]
}
So, for some reason the JSON response is not accepting more fields pageNrand totalPages.
What is wrong here?.
Each assignment overwrites your array. You need to update it instead:
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response = [];
$response['pageNr'] = $page;
$response['totalPages'] = $totalPages;
$response['products'] = $res2;
Try;
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response .= ['pageNr' => $page];
$response .= ['totalPages' => $totalPages];
$response .= ['products' => $res2];
Related
I have this data but I can't parse it in the way I want. this is what I get:
{
"navigations": {
"title": "Facebook",
"link": "https://facebook.com",
"behavior": "EXTERNAL"
}
}
And what I expect to see:
{
"navigations": [
{
"title": "Facebook",
"url": "https://facebook.com",
"behavior": "INAPP"
},
{
"title": "Youtube",
"url": "https//youtube.com",
"behavior": "INAPP"
}
]
}
I have more results in my database but not more than 12 result so, i want to fetch data in the format i expect. I tried to do it using fetch_array but no success.
This is my PHP code:
$query_update_navigations = $db->prepare("SELECT title, link, behavior FROM navigation_tabs WHERE secret_api_key=?");
$query_update_navigations->bind_param("s", $_SESSION['secret_api_key']);
$query_update_navigations->execute();
$rows = array();
$result = $query_update_navigations->get_result();
while($rows1 = $result->fetch_assoc()) {
$rows['navigations'] = $rows1;
}
$store_path = '../apis/navigation_tabs/';
$file_name = $_SESSION['secret_api_key'] . '.json';
$sign_constants = json_encode($rows);
file_put_contents($store_path . $file_name, $sign_constants);
I searched for an answer but nothing solved my issue :(
You need to push the row onto the array, not overwrite it each time.
$rows = array('navigations' => []);
$result = $query_update_navigations->get_result();
while($rows1 = $result->fetch_assoc()) {
$rows['navigations'][] = $rows1;
}
I amnot familiar php arrays. Therefore I couldn't solve that problem :
My data comes from database. I didn't post database connection parts, they work perfectly. As I understand I need to use multidimensional array. My Json format should be like this
{
"monthly":[
{
"id":1,
"name":"This is a JSON event",
"startdate":"2016-9-15",
"enddate":"2016-9-15",
"starttime":"12:00",
"endtime":"2:00",
"color":"#FFB128",
"url":""
},
{
"id":2,
"name":"This is a JSON event",
"startdate":"2019-3-25",
"enddate":"2019-3-25",
"starttime":"12:00",
"endtime":"23:00",
"color":"#EF44EF",
"url":""
}
]
}
My PHP script (relevant part) :
try {
$q = "SELECT * FROM eventcalendar";
$res = $db->prepare($q);
$res->execute();
if ($res->rowCount() != 0) {
$data = array('monthly' => array());
$push_array = array();
foreach ($res as $key) {
$data['monthly']['id'] = $key['id'];
$data['monthly']['name'] = $key['name'];
$data['monthly']['startdate'] = $key['startdate'];
$data['monthly']['enddate'] = $key['startdate'];
$data['monthly']['color'] = $key['color'];
$data['monthly']['starttime'] = 12;
$data['monthly']['endtime'] = 12;
$data['monthly']['url'] = "";
array_push($push_array, $data);
}
file_put_contents('../js/events.json', json_encode($push_array));
echo('<div class="alert alert-success resultsuccess" ><h4 class="alert-heading">Successful!</h4></div>');
}
} catch (Exception $e) {
echo('<div class="alert alert-danger resultsuccess" >'.'Error: '.$e->getMessage().'</div>');
}
I get that JSON format
[
{
"monthly":{
"id":"1",
"name":"test1",
"startdate":"2019-03-29",
"enddate":"2019-03-29",
"color":"#ffb128",
"starttime":12,
"endtime":12,
"url":""
}
},
{
"monthly":{
"id":"2",
"name":"test2",
"startdate":"2019-03-29",
"enddate":"2019-03-29",
"color":"#4263e6",
"starttime":12,
"endtime":12,
"url":""
}
}
]
Thanks for reading...
Your problem is that you are creating new arrays with a monthly index on each pass through your loop, instead of pushing the new data into the existing monthly array. Try this instead:
if ($res->rowCount() != 0) {
$push_array = array('monthly' => array());
$data = array();
foreach ($res as $key) {
$data['id'] = $key['id'];
$data['name'] = $key['name'];
$data['startdate'] = $key['startdate'];
$data['enddate'] = $key['startdate'];
$data['color'] = $key['color'];
$data['starttime'] = 12;
$data['endtime'] = 12;
$data['url'] = '';
array_push($push_array['monthly'], $data);
}
i want this json format in php but i unable to do this.
{
"couresList_PVP": [
{
"pvp_ad_chptr_id": "9",
"pvp_ad_chptr_un_id": "1526249608",
"pvp_ad_chptr_name": "54654",
"offer_chapter_PVP": [
{
"pvp_ad_chptr_offr_id": "4",
"pvp_ad_chptr_un_id": "1526249608",
"pvp_ad_chptr_offr_un_id": "Offer-1526249608"
},
{
"pvp_ad_chptr_offr_id": "3",
"pvp_ad_chptr_un_id": "1526249608",
"pvp_ad_chptr_offr_un_id": "Offer-1526249608"
}]
},]
}
my PHP code is here. how I will do this? I'll get JSON response but different array not in a single with the array in array.
$sql = mysqli_query($this->db,"SELECT * from `pvp_admin_chptr_list` order by pvp_ad_chptr_id desc");
if(mysqli_num_rows($sql) > 0){
while($res=mysqli_fetch_assoc($sql)){
$url=$this->site_url.'images_console/chapter_banner_console/'.$res['pvp_ad_chptr_banner'];
$video=$this->site_url.'video_console/'.$res['pvp_ad_chptr_video_name'];
$images=array('pvp_ad_chptr_banner'=>$url,'pvp_ad_chptr_video_name'=>$video);
$data['couresList_PVP'][]=array_merge($res,$images);
$ofr_sql = mysqli_query($this->db,"SELECT * from `pvp_admin_chptr_offers` where pvp_ad_chptr_un_id='$res[pvp_ad_chptr_un_id]' order by pvp_ad_chptr_offr_id desc");
if(mysqli_num_rows($ofr_sql) > 0){
while($ofr_res=mysqli_fetch_assoc($ofr_sql)){
$data['offer_chapter_PVP'][]=$ofr_res;
}
}else{
$data['offer_chapter_PVP'][]=array("status"=>"No Data FOund");
}
}
//$data2=array_merge($data['couresList_PVP'],$data['offer_chapter_PVP']);
//$data[]=array_push( $data['couresList_PVP'],$data['offer_chapter_PVP']);
//$data=
// If success everything is good send header as "OK" and user details
$this->response($this->json($data), 200);
}
you can use combination of array and then encode it in json. please check below code.
$response = array();
$responseObj = array();
$courseList = array();
$courseArr = array();
while($res=mysqli_fetch_assoc($sql)){
$courseList['pvp_ad_chptr_id'] = $res['id'];
$courseList['pvp_ad_chptr_un_id'] = $res['pvp_ad_chptr_un_id'];
$courseList['pvp_ad_chptr_name'] = $res['pvp_ad_chptr_name'];
$ofr_sql = mysqli_query($this->db,"SELECT * from `pvp_admin_chptr_offers` where pvp_ad_chptr_un_id='$res[pvp_ad_chptr_un_id]' order by pvp_ad_chptr_offr_id desc");
if(mysqli_num_rows($ofr_sql) > 0){
while($ofr_res=mysqli_fetch_assoc($ofr_sql)){
$courseList['offer_chapter_PVP'][]=$ofr_res;
}
}else{
$courseList[$i]['offer_chapter_PVP'][]=array("status"=>"No Data FOund");
}
$courseArr[] = $courseList;
}
$response['couresList_PVP'] = $courseArr;
$responseObj = $response;
echo '<pre>';
echo json_encode($responseObj);
echo '</pre>';
(i'm a bit new in PHP / JSON) i have a PHP page that send me an array of informations to an Android application and i need to change the Json "format" so i can manage it in my Android application.
I tried adding the array to a PHP class but i only get errors.
From this (this is just an example):
[
{
"updated_at":"2012-03-02 21:06:01",
"fetched_at":"2012-03-02 21:28:37.728840",
"description":null,
"language":null,
"title":"JOHN",
"url":"http://rus.JOHN.JOHN/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f4791da203d0c2d76000035",
"modified":"2012-03-02 23:28:58.840076"
},
{
"updated_at":"2012-03-02 14:07:44",
"fetched_at":"2012-03-02 21:28:37.033108",
"description":null,
"language":null,
"title":"PETER",
"url":"http://PETER.PETER.lv/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f476f61203d0c2d89000253",
"modified":"2012-03-02 23:28:57.928001"
}
]
To this (other example):
{"master":[
{
"updated_at":"2012-03-02 21:06:01",
"fetched_at":"2012-03-02 21:28:37.728840",
"description":null,
"language":null,
"title":"JOHN",
"url":"http://rus.JOHN.JOHN/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f4791da203d0c2d76000035",
"modified":"2012-03-02 23:28:58.840076"
},
{
"updated_at":"2012-03-02 14:07:44",
"fetched_at":"2012-03-02 21:28:37.033108",
"description":null,
"language":null,
"title":"PETER",
"url":"http://PETER.PETER.lv/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f476f61203d0c2d89000253",
"modified":"2012-03-02 23:28:57.928001"
}
]
}
My PHP page that create the JSON array:
<?php
class card{
public $id = 0;
public $name = "";
public $value = 0;
public $imgpath = "";
public $rarity = "";
public $litness = 0;
public $dankness = 0;
public $expansion = "";
}
$b= array();
$connessione = mysqli_connect("", "", "", "");
$query = "insert_query_here";
$risultato = mysqli_query($connessione, $query);
while($row = mysqli_fetch_assoc($risultato)){
$card = new card();
$card->id = $row['id_card'];
$card->name = $row['name'];
$card->value = $row['value'];
$card->imgpath = $row['imgpath'];
$card->rarity = $row['name_rarity'];
$card->litness = $row['litness'];
$card->dankness = $row['dankness'];
$card->expansion = $row['expansion_name'];
$b[] = $card;
}
$out = array_values($b);
print json_encode($out);
Try the following:
$out = ['master' => array_values($b)];
print json_encode($out);
This will add the key master in the main array, and the rest will be nested in it.
I have a mysql table (name:"messages") that has three columns as below:
messageID, fromUserID, content
I wish to have a json output using php script like following format; I need to seprate messages of each user (fromUserID column).
JSONOutput:
{
"newCount":"x",
"messages":
[
{
"fromUserID":"x",
"messagesArray":
[
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"}
]
},
{
"fromUserID":"y",
"messagesArray":
[
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"}
]
},
{
"fromUserID":"z",
"messagesArray":
[
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"}
]
}
]
}
My PHP Script:
$query = mysqli_query($con,"SELECT * FROM messages ORDER BY fromUserID");
$outputArray = array();
$outputArray['hasNew'] = mysqli_num_rows($query);
$messagesArray = array();
if($query)
{
while($row = mysqli_fetch_assoc($query))
{
$MSGArray = array();
$messagesArray['fromUserID'] = $row['fromUserID'];
$MSGArray['messageID'] = $row['messageID'];
$MSGArray['content'] = $row['content'];
$messagesArray['MessagesArray'][] = $MSGArray;
}
$outputArray['Messages'][] = $messagesArray;
}
echo json_encode($outputArray);
But with above script I give a wrong result as below:
{
"hasNew":6,
"Messages":
[
{
"fromUserID":"24",
"MessagesArray":
[
{"messageID":"4","content":"test"},
{"messageID":"3","content":"test"},
{"messageID":"6","content":"test"},
{"messageID":"5","content":"test"},
{"messageID":"1","content":"test"},
{"messageID":"2","content":"test"}
]
}
]
}
My PHP Script just using last fromUserID value to grouping messages !!!
Please let me know where I'm wrong ...
Try it
if($query)
{
while($row = mysqli_fetch_assoc($query))
{
$MSGArray = array();
$messagesArray[$row['fromUserID']]['fromUserID'] = $row['fromUserID'];
$MSGArray['messageID'] = $row['messageID'];
$MSGArray['content'] = $row['content'];
$messagesArray[$row['fromUserID']]['MessagesArray'][] = $MSGArray;
}
foreach($messagesArray as $value) {
$outputArray['Messages'][] = $value;
}
}