I have a json that is look like this
{
"data": [
data here
]
}
and here is how i fill it up
$json = array();
foreach ($result as $key => $value) {
$json['data'][] = $value;
}
and here is how i display it
echo json_encode($json,JSON_PRETTY_PRINT);
what if the data for is empty? how can I display an empty json because my php only display [] when it is empty
like maybe something like this
{
"data": [
]
}
I would suggest explicitly defining your structure before adding records to your 'data' index. Currently, the 'data' property is only created during result iteration, which is why you're seeing a string of [] wen there are no records.
$json = array( 'data' => array() );
This will also help to avoid any warnings/notices generated by PHP.
Related
I am trying to to pull data from an API response. but can't seem to figure out how to navigate to the "statistics" section of the response.
Here is the responce in short
{
"response": [
{
"player": {
},
"statistics": [
{
"team": {
"id": 49,
"name": "Chelsea",
"logo": "some data"
}
}
]
}
]
}
The code I have at the moment is as follows:
$leaguelist = array();
if (! empty( $desc-> response)) {
foreach ($desc->response as $players){
$player['id'] = $players->player->id;
$player['name'] = $players->player->name;
$player['first_name'] = $players->player->firstname;
$player['last_name'] = $players->player->lastname;
$player['age'] = $players->player->age;
$player['dob'] = $players->player->birth->date;
$player['pob'] = $players->player->birth->place;
$player['cob'] = $players->player->birth->country;
$player['nationality'] = $players->player->nationality;
$player['height'] = $players->player->height;
$player['weight'] = $players->player->weight;
$player['photo'] = $players->player->photo;
$player['team_logo'] = $players->statistics->team->logo;
$leaguelist[] = $player;
}
}
I am able to pull and display all data from the player directory just having problems working out the code to get onto the statistics
I have tried
$player['team_logo'] = $players->statistics->team->logo;
I can't really research much into this as I don't know what "this" is called, any help would be great as i am a hobbyist and have ran out of ideas.
Thank you in advance
Assuming that the response you show is in JSON, and you've then parsed it with json_decode, there are only two types of structure you need to know about:
Anything in [] square brackets is an array, and is accessed as numbered items [0], [1], etc; or with a foreach loop
Anything in {} curly brackets is an object, and is accessed using ->foo, etc
So working from the outside, we have:
An outer object { which you've called $desc
... from which we want key "response": $desc->response ...
Then an array [, which you've looped over: foreach ($desc->response as $players)
Then in the first item of that array, an object { which the loop assigns to $players ...
... from which we want key "statistics": $players->statistics ...
Then an array [ ...
... from which we could take the first item: $stat = $players->statistics[0]; or loop over all the items: foreach ( $players->statistics as $stat )
Each item is then an object { ...
... from which we want the "team" key: $stat->team
Which is an object { ...
... from which we want the "id" key: $stat->team->id
If we just wanted that one value, we could write it all in one go: $desc->response[0]->statistics[0]->team->id. It doesn't matter how deep we're nesting, we just need to look for the [ or { to see what to do next.
statistics is an array. So if you want an item from within it, you need to refer to an index of that array which contains the item.
E.g.
$player['team_logo'] = $players->statistics[0]->team->logo;
to get the first item.
I'm currently building an array off of an object and I've got one element called images that has multiple sub elements called 'urls' structured like so
categories": [
{
"images": [
{
"urls": [
"path/test.jpg",
"path/test2.jpg",
"path/test3.jpg"
],
},
{
"urls": [
"path/test4.jpg",
"path/test5.jpg",
"path/test6.jpg"
],
},
{
"urls": [
"path/test7.jpg",
"path/test8.jpg",
"path/test9.jpg"
],
},
]
The values there don't have keys, it's just the url path but I'd like to add these to my $groupItem array and just have each url be it's own element on the same level as the group number (basically I'm exporting and need each url as it's own column)
The structure I want
0 =>"path/test.jpg",
1 =>"path/test2.jpg",
2 =>"path/test3.jpg"
3 =>"path/test4.jpg",
4 =>"path/test5.jpg",
5 =>"path/test6.jpg"
6 =>"path/test7.jpg",
7 =>"path/test8.jpg",
8 =>"path/test9.jpg"
The loop/array:
foreach($prices->groups as $group){
$groupItem = array();
$groupItem["number"] = $group->number;
foreach($group->images as $images){
$groupItem["urls"] = $images->urls;
}
}
How can I simply just add on any url to the groupItem level of that array?
Outside the outer loop, init the value to an empty array:
$groupItem["urls"] = [];
Then use the empty array reference operator to append new values to the end of an array:
foreach($group->images as $images){
$groupItem["urls"][] = $images->urls; // add this url to the end of the list
}
Alternatively, use array_push():
foreach($group->images as $images){
array_push($groupItem["urls"], $images->urls);
}
I think you can probably also skip the inner loop and just use the array explode operator like this:
array_push($groupItem["urls"], ...$images->urls);
You might also use array_column with (from php 5.6) a variable length argument list:
For example, for the images which contains an array of objects where each object has a property urls and contains an array of image urls:
foreach ($prices->groups as $group) {
$groupItem = array();
$groupItem["number"] = $group->number;
$groupItem= array_merge($groupItem, ...array_column($group->images, "urls"));
}
Demo
I am setting up a Jquery autosuggest using ajax and I have a simple query to the database which returns 5 suggestions. The fields are company and id, so I get
$result['id']
$result['company']
for each row of the returned database suggestiions
This works fine and currently I loop over the results
foreach ($result as $item) {
$suggest[] = $item['company'];
}
echo json_encode($suggest);
I want though to add these so the company is a label and id is a value, something like
"value": "A Company", "data": "20"
This I can then encode and use in my autosuggest.
Thanks in advance!
You have to save an array to main array like this
foreach ($result as $item) {
$suggest[] = [
'value' => $item['company'],
'data' => $item['id'],
]
}
echo json_encode($suggest);
And it should return something like this
[
{
'value': 'Some value',
'data' : item id
}
]
i will recommend you create an array, next create 2 more arrays as values for the value and data keys.
like this.
$arr=array();
$arr['value']=array();
$arr['data']=array();
while($suggest=mysql_fetch_assoc($result)){
array_push($arr['value'],$suggest['id']);
array_push($arr['data'],$suggest['company']);
}
echo "<pre>";
print_r($arr);
note that with this solution, if you delete an entry in either value or data
be ready to delete the corresponding entry in the other array.
others may be able to improve this or even offer a better approach.
I want to add some string before the data derived from mySQL. And output them in JSON. I can fetch out the data from mySQL right for my needs. But I cannot add the prefix string to the right format.
The expected json format
{
"message": "",//i can do this
"value": [//but I can't do this the "value":[
{
"excName": "Mark",
"excSup": "chunyun",
"excId": 20001
}, {
"excName": "orion-01",
"excSup": "orion-01",
"excId": 20000
}
]
}
PHP
while ($rec_qXcur=mysqli_fetch_assoc($sql_qXcur)){
$data[] = array(
"excId"=>$rec_qXcur['exc_id'],
"excTitle"=>$rec_qXcur['exc_name'],
"excSup"=>$rec_qXcur['exc_sup']
);
}
//return json data
echo json_encode($data);
From PHP I got this :
{
"message":"",
//"value":[//this is missing
"0":{//not need
"excId":"234",
"excTitle":"Simon Cabaret - Regular Seat ",
"excSup":"simon"
},
"1":{//not need
"excId":"245",
"excTitle":"Simon Cabaret - VIP Seat (01Nov15 - 30Apr16)",
"excSup":"simon"
}
According to the expected json format. I missed "value":[. I tried adding it to the $data but it's not working.
You are just adding them to data. You need to add them to the value array.
So json_encode() is probably creating an object literal {} because your array has both named elements and sequential elements. Once it only contains sequential elements, json_encode() should (I believe) return an array literal [];
$data = array(
'message' => 'Your message here',
'value' => array()
);
while ($rec_qXcur=mysqli_fetch_assoc($sql_qXcur)){
$data['value'][] = array(
"excId"=>$rec_qXcur['exc_id'],
"excTitle"=>$rec_qXcur['exc_name'],
"excSup"=>$rec_qXcur['exc_sup']
);
}
echo json_encode($data);
I am trying to dynamicaly generate data in json for jQuery gantt chart. I know PHP but am totally green with JavaScript. I have read dozen of solutions on how dynamicaly add data to json, and tried few dozens of combinations and nothing. Here is the json format:
var data = [{
name: "Sprint 0",
desc: "Analysis",
values: [{
from: "/Date(1320192000000)/",
to: "/Date(1322401600000)/",
label: "Requirement Gathering",
customClass: "ganttRed"
}]
},{
name: " ",
desc: "Scoping",
values: [{
from: "/Date(1322611200000)/",
to: "/Date(1323302400000)/",
label: "Scoping",
customClass: "ganttRed"
}]
}, <!-- Somoe more data-->
}];
now I have all data in php db result. Here it goes:
$rows=$db->fetchAllRows($result);
$rowsNum=count($rows);
And this is how I wanted to create json out of it:
var data='';
<?php foreach ($rows as $row){ ?>
data['name']="<?php echo $row['name'];?>";
data['desc']="<?php echo $row['desc'];?>";
data['values'] = {"from" : "/Date(<?php echo $row['from'];?>)/", "to" : "/Date(<?php echo $row['to'];?>)/", "label" : "<?php echo $row['label'];?>", "customClass" : "ganttOrange"};
}
However this does not work. I have tried without loop and replacing php variables with plain text just to check, but it did not work either. Displays chart without added items. If I add new item by adding it to the list of values, it works. So there is no problem with the Gantt itself or paths. Based on all above I assume the problem is with adding plain data to json. Can anyone please help me to fix it?
First of all you're adding properties to string instead of building object. If you really want to do that this way:
var data = [], row;
<?php foreach ($rows as $row) : ?>
row = {};
row.name ="<?php echo $row['name'];?>";
row.desc ="<?php echo $row['desc'];?>";
row.values = {"from" : "/Date(<?php echo $row['from'];?>)/", "to" : "/Date(<?php echo $row['to'];?>)/", "label" : "<?php echo $row['label'];?>", "customClass" : "ganttOrange"};
data.push(row);
<?php endforeach; ?>
Anyway it is unsafe (and result is normal JS code, not proper JSON object - but as you're assigning it to variable then I suppose it does not have to be in strict JSON format)
Better approach would be to build data structure in PHP and use json_encode function to generate JSON data for JavaScript:
<?php
$data = array();
foreach ($rows as $row) {
$data[] = array(
'name' => $row['name'],
'desc' => $row['desc'],
'values' => array(array(
'from' => '/Date('.$row['from'].'>)/',
'to' => '/Date('.$row['to'].')/',
'label' => $row['label'],
'customClass' => 'ganttOrange',
))
);
}
?>
var data = <?php echo json_encode($data); ?>;
Quick Answer
As stated previously, this problem is easily resolved using the PHP json_encode function.
The trick to understanding how to do this easily is to understand the composite data structure that you are trying to work with.
Overview
What you are dealing with is a general programming concept called a "composite data structure". The trick to understanding this is to realize that the PHP and the JavaScript that you are attempting to manage are just two different representations of the exact same thing.
Once this concept sinks in, it will be easy to relate to what the users Musa and dev-null-dweller have already explained.
The straightforward way to solve this issue is to simply build a composite data structure in PHP and then translate it into JSON (aka JavaScript) using the built-in native methods of PHP's json_encode and json_decode.
Instead of doing all the statements, you should treat each $row as a composite data structure and use the PHP json functions.
The following example should give you a head start, simply compare it to the data you are trying to work with and change accordingly.
Example 001
// This is a PHP composite data structure [ a nested array ]
// represented in PHP. When you run this code you will get the
// output of Result 001
$user_profile = Array(
main => Array(
first_name => "_blank_",
last_name => "_blank_",
sex => "_blank_",
age => "_blank_",
),
guardian => Array(
first_name => "",
last_name => "",
),
children => Array(
0 => Array(
first_name => "Sally",
last_name => "Shaw",
),
1 => Array(
first_name => "Scott",
last_name => "Shaw",
),
),
);
// This is some sample PHP code you can use to modify
// the composite data structure (modify the "_blank_" values)
//
$user_profile["main"]["first_name"] = "Archibald";
$user_profile["main"]["last_name"] = "Shaw";
$user_profile["main"]["age"] = "33";
$user_profile["main"]["sex"] = "male";
// This is some sample PHP code you can use to modify
// the composite data structure (add a new child)
//
$user_profile["children"][2] = Array();
$user_profile["children"][2]["first_name"] = "Carrie";
$user_profile["children"][2]["last_name"] = "Shaw";
// This is the PHP code you can use to transform from PHP to JSON
$result = json_encode( $user_profile );
print_r( $result );
Result 001 (formatted for easy readability)
{
"main":{
"first_name":"Archibald",
"last_name":"Shaw",
"sex":"male",
"age":"33"
},
"guardian":{
"first_name":"",
"last_name":""
},
"children":[
{
"first_name":"Sally",
"last_name":"Shaw"
},
{
"first_name":"Scott",
"last_name":"Shaw"
},
{
"first_name":"Carrie",
"last_name":"Shaw"
}
]
}
Conclusion
Using the example above, you should first do a print_r of the PHP variable you are trying to work with and get an idea of the overall structure. Once you know this, it is an easy step to convert it to JSON using the built-in PHP json_encode function.
References
http://en.wikibooks.org/wiki/PHP_Programming/Data_Structures#The_Basics
http://en.wikipedia.org/wiki/Composite_type
var data=[];
<?php
foreach ($rows as $row)
{
$obj = array(
'name' => $row['name'],
'desc' => $row['desc'],
'values' => array(
array(
"from" => "/Date({$row['from']})/",
"to" => "/Date({$row['to']})/",
"label" => $row['label'],
"customClass" => "ganttOrange",
)
)
);
$objJson = json_encode($obj);
echo "data.push({$objJson});\n";
}
?>
You should create the data structure in php and echo it out with json_encode.
<?php
$data = array();
foreach ($rows as $row){
$item = array();
$item['name']=$row['name'];
$item['desc']=$row['desc'];
$item['values']= array("from" => "/Date{$row['from']})/",
"to" => "/Date({$row['to']})/",
"label" => $row['label'],
"customClass" => "ganttOrange");
$data[] = $item;
}
echo "\nvar data = ".json_encode($data).";\n";