Change JSON output "format" - PHP - php

(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.

Related

Generating desirable JSON format in PHP

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);
}

Catch Tweets with JSON and sort by likes?

I am currently running a wordpress backend and want to display some tweets based on hastags on my website. For the general API request and database storage, I use this function:
private function parseRequest($json) {
$tmp = $json;
$result = array();
if (isset($json['statuses'])) {
$tmp = $json['statuses'];
}
if (isset($tmp) && is_array($tmp)){
foreach ($tmp as $t) {
$this->image = null;
$this->media = null;
$tc = new \stdClass();
$tc->feed_id = $this->id();
$tc->id = $t['id_str'];
$tc->type = $this->getType();
$tc->nickname = '#'.$t['user']['screen_name'];
$tc->screenname = (string)$t['user']['name'];
$tc->userpic = str_replace('.jpg', '_200x200.jpg', str_replace('_normal', '', (string)$t['user']['profile_image_url']));
$tc->system_timestamp = strtotime($t['created_at']);
$tc->text = $this->getText($t);
$tc->userlink = 'https://twitter.com/'.$t['user']['screen_name'];
$tc->permalink = $tc->userlink . '/status/' . $tc->id;
$tc->media = $this->getMedia($t);
#$tc->additional = array('shares' => (string)$t['retweet_count'], 'likes' => (string)$t['favorite_count'], 'comments' => (string)$t['reply_count']);
if ($this->isSuitablePost($tc)) $result[$tc->id] = $tc;
}
}
return $result;
}
Now I am looking for a function that counts all the variable in the "additional array together e.g. shares + likes + comments and sorts all posts based on the resulting number.
I am using the standard wordpress sql database. I cannot find a solution or I am just blind.
Thanks in regards
You could use a simple usort function:
usort($tc, function($a, $b) {
$a_sum = array_sum($a->additional);
$b_sum = array_sum($b->additional);
if ($a_sum == $b_sum) {
return 0;
}
return ($a_sum < $b_sum) ? -1 : 1;
});

Generate JSON response on server with JsonArray and single fields

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

getting error to display all record in php json

I am trying to display all records using jason in php.
but display all filed with null value.
I'm using postman for testing purpose.
I don't know what is the problem with that code. I getting null value only.
here is my code :
<?php
header('Content-Type: application/json');
$checkFields = "";
$REQUEST = $_SERVER['REQUEST_METHOD'];
if ($REQUEST == "POST")
{
include "DB/db.php";
$userlist = mysql_query("SELECT * FROM reg_services");
if(mysql_num_rows($userlist) > 0)
{
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
$json = array("success" => 1, "All_User_List" => $ph);
$jsonarray = json_encode($json);
}
}
else
{
$json = array("success" => 0, "message" => "Invalid Request Type(Use POST Method)");
$jsonarray = json_encode($json);
}
echo $jsonarray;
?>
please help me if you are know what is the error in code.
just replace this code with old one
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_array($userlist))
{
$ph[$p] = array();
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
You need to tell PHP about arrays
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p] = array(); // let PHP know it is an array
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
just replace this while loop condition with olde one.
while($userlistdata = mysql_fetch_array($userlist))
now it's work

php while loop error

I have a PHP MySQL fetch while loop as shown below in my script:
$result2211 = mysql_query("select * from products where is_config = 'yes' ");
while($row2211 = mysql_fetch_assoc($result2211))
{
$sn = $row2211['sn'];
$allparrentselectq = mysql_query("SELECT * FROM parrentpro where parrentsn = $sn");
while($allparrentselect = mysql_fetch_assoc($allparrentselectq))
{
$childarr = unserialize($allparrentselect['childsn']);
$subpro = '{"catname":"'.$allparrentselect['childname'].'",';
$i = 0;
foreach($childarr as $childarr):
$subpro .= '"Pro'.$i++.'":"'.$childarr.'",';
endforeach;
$subpro1[] = substr($subpro, 0, -1)."}";
$subproa = "[".implode(",",$subpro1)."]";
}
$prodObj2 = new ProductDetails();
$prodObj2->productname = $row2211['productname'];
$prodObj2->price = $row2211['productprice'];
$prodObj2->discount = $row2211['discount'];
$prodObj2->discountprice = $row2211['discountprice'];
$prodObj2->imageURL = $row2211['productimageurl'];
$prodObj2->category = $row2211['productcat'];
$prodObj2->configurablepone = $subproa;
$prodObj2->configurable = 'yes';
array_push($totArr, $prodObj2);
}
In that I have a problem. I get the result as like below (JSON):
[
{
"productname":"Veg.Pizaa",
"price":"350",
"discount":"",
"discountprice":"350",
"imageURL":"http:\/\/farm8.staticflickr.com\/7154\/6694188161_9ee692d854_s.jpg",
"category":"Pizaa",
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"}],
"configurable":"yes"
},
{
"productname":"Core i7 Pc",
"price":"48000",
"discount":"2",
"discountprice":"47040",
"imageURL":"http:\/\/www.4to40.com\/images\/science\/Basic_Computer_Parts\/Computer.jpg",
"category":"Pc",
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},{"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"},{"catname":"Harddisk","Pro0":"Segate 500Gb","Pro1":"Samsung 250Gb"},{"catname":"Ram","Pro0":"8Gb Ram","Pro1":"4Gb Ram","Pro2":"2Gb Ram"}],
"configurable":"yes"
}
]
But I need the result as like below:
[
{
"productname":"Veg.Pizaa",
"price":"350",
"discount":"",
"discountprice":"350",
"imageURL":"http:\/\/farm8.staticflickr.com\/7154\/6694188161_9ee692d854_s.jpg",
"category":"Pizaa",
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"}],
"configurable":"yes"
},
{
"productname":"Core i7 Pc",
"price":"48000",
"discount":"2",
"discountprice":"47040",
"imageURL":"http:\/\/www.4to40.com\/images\/science\/Basic_Computer_Parts\/Computer.jpg",
"category":"Pc",
"configurablepone":[{"catname":"Harddisk","Pro0":"Segate 500Gb","Pro1":"Samsung 250Gb"},{"catname":"Ram","Pro0":"8Gb Ram","Pro1":"4Gb Ram","Pro2":"2Gb Ram"}],
"configurable":"yes"
}
]
As you can see configurablepone JSON is getting repeated for every loop so I am getting the value of the first product in second product also but I need to seperate like below:
First Product As Like Below
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},{"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"}]
Second Product As Like Below
"configurablepone":[{"catname":"Harddisk","Pro0":"Segate 500Gb","Pro1":"Samsung 250Gb"},{"catname":"Ram","Pro0":"8Gb Ram","Pro1":"4Gb Ram","Pro2":"2Gb Ram"}]
I have tried changing the loop but I haven't found any solutions. Kindly help me to solve this.
I think, your problem in line $subpro1[] = substr($subpro, 0, -1)."}";.
So, first call of this line save data from "Veg.Pizaa" into $subpro1[0].
Second call of this line save data from "Core i7 Pc" into $subpro1[1].
Then, line $subproa = "[".implode(",",$subpro1)."]"; merged all array elements.
Just Use unset($subpro1); after the array_push($totArr, $prodObj2);.
Below Is An example Source
Try This One This May Work
$result2211 = mysql_query("select * from products where is_config = 'yes' ");
while($row2211 = mysql_fetch_assoc($result2211))
{
$sn = $row2211['sn'];
$allparrentselectq = mysql_query("SELECT * FROM parrentpro where parrentsn = $sn");
while($allparrentselect = mysql_fetch_assoc($allparrentselectq))
{
$childarr = unserialize($allparrentselect['childsn']);
$subpro = '{"catname":"'.$allparrentselect['childname'].'",';
$i = 0;
foreach($childarr as $childarr):
$subpro .= '"Pro'.$i++.'":"'.$childarr.'",';
endforeach;
$subpro1[] = substr($subpro, 0, -1)."}";
$subproa = "[".implode(",",$subpro1)."]";
}
$prodObj2 = new ProductDetails();
$prodObj2->productname = $row2211['productname'];
$prodObj2->price = $row2211['productprice'];
$prodObj2->discount = $row2211['discount'];
$prodObj2->discountprice = $row2211['discountprice'];
$prodObj2->imageURL = $row2211['productimageurl'];
$prodObj2->category = $row2211['productcat'];
$prodObj2->configurablepone = $subproa;
$prodObj2->configurable = 'yes';
array_push($totArr, $prodObj2);
unset($subpro1);
}
while($allparrentselect = mysql_fetch_assoc($allparrentselectq))
{
$childarr = unserialize($allparrentselect['childsn']);
$subpro = '{"catname":"'.$allparrentselect['childname'].'",';
$i = 0;
foreach($childarr as $childarr):
$subpro .= '"Pro'.$i++.'":"'.$childarr.'",';
endforeach;
$subpro1[] = substr($subpro, 0, -1)."}";
$subproa = "[".implode(",",$subpro1)."]";
$subpro1 = array();
}
try this in second while loop

Categories