How to create a JSON array in php? - php

I am trying to create a simple android application that takes data from a database and displays it in a list format on the android screen. I made a php script that queries the database and returns a json object. I convert the json object into json array and extract the relevant data for display. But I am getting this error "JSONException: type org.json.JSONObject cannot be converted to JSONArray".
Following is my php script -
// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);
$username = $_POST['username'];
$events = $db->viewAttendingEvent($username);
if ($events) {
$response["success"] = 1;
$response["event"]["owner"] = $events["owner"];
$response["event"]["friendsnames"] = $events["friendsnames"];
$response["event"]["vote"] = $events["vote"];
$response["event"]["accepted"] = $events["accepted"];
$response["event"]["eventname"] = $events["eventname"];
$response["event"]["eventnumber"] = $events["eventnumber"];
$response["event"]["created_at"] = $events["created_at"];
echo json_encode($response);
This is the json which I receive back :
{
"tag": "view_invitations",
"success": 1,
"error": 0,
"event": {
"owner": "jkkkkoopp",
"friendsnames": "don",
"vote": "0",
"accepted": "f",
"eventname": "yyy",
"eventnumber": "11",
"created_at": "2014-05-29 22:27:31.843528"
}
}
I am trying to extract 'event' from this json object, which is not an array.
it should be
{
"event": [
{
"owner": "jkkkkoopp",
"friendsnames": "don",
"vote": "0",
"accepted": "f",
"eventname": "yyy",
"eventnumber": "11",
"created_at": "2014-05-2922: 27: 31.843528"
}
]
}
Can someone help me how to make this a valid jsonArray ? Thanks

If you're looking to get a JavaScript 'Array' (from which I mean an Object with nothing but integer keys) then you need to only have integer keys in your PHP Array.
This article is a pretty good resource and explains some of the differences between arrays and objects in javascript. The relevant quote here comes from the What Arrays Are section (emphasis mine):
Javascript arrays are a type of object used for storing multiple
values in a single variable. Each value gets numeric index and may be
any data type.

No it should not be what you proposed it should be. If that were the case you would have to have your php be this:
$response["event"][0]["owner"] = $events["owner"];
$response["event"][0]["friendsnames"] = $events["friendsnames"];
$response["event"][0]["vote"] = $events["vote"];
$response["event"][0]["accepted"] = $events["accepted"];
$response["event"][0]["eventname"] = $events["eventname"];
$response["event"][0]["eventnumber"] = $events["eventnumber"];
$response["event"][0]["created_at"] = $events["created_at"];
The way you have it now is event is an associative array so it converts it to an object. You are expecting that event = an array of objects. So you need to either change your php code to make event be an array of objects (as demonstrated above) or you need to modify your expectations to have event = an object.

Related

JSON object with array header

this question comes from the posting I found here:
DataTables Multiple Tables from Multiple JSON Arrays
I'd like to know the simplest and best way to generate the JSON below. I can see the pattern is 'JSON object -> Array Header -> Array -> JSON object' but I do not know how to do this in PHP, from a mySQLi query result. I imagine having a mySQL table with a 'policies' and 'services' column so the query might look something like:
Select name, id, score, type from myTable where type = 'policies' and
type = 'services'
And the result would come back something like:
name id score type
A 1 0 policies
B 2 0 services
But then how would I take that query and generate this JSON in php?
{
"Policies": [
{
"name": "A",
"id": "1",
"score": "0"
}
],
"Services": [
{
"name": "B",
"id": "2",
"score": "0"
}
]
}
Thanks for your help!
Start by creating the new empty array.
Then, iterate through the result and add it in the correct sub-array:
$new = [];
foreach ($result as $item) {
// Uppercase the first character
$type = ucfirst($item['type']);
if (!isset($new[$type])) {
// This type doesn't exist in the new array yet, let's create it.
$new[$type] = [];
}
// Add the item
$new[$type][] = $item;
}
// Output it as json
echo json_encode($new, JSON_PRETTY_PRINT);
The above code will also work if new types are added to the database.
PS. The JSON_PRETTY_PRINT argument is just to make the json string a bit more readable while developing. When everything looks good, you can remove it.

Get specific data in variable array JSON with jQuery PHP

I'm trying to get specific data from a JSON file (url) and save that data in a PHP variable.
The JSON comes from an url. For example:
https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/Viducius?api_key=secret
The JSON file:
{
"viducius": {
"id": 26541044,
"name": "Viducius",
"profileIconId": 591,
"revisionDate": 1480517139000,
"summonerLevel": 30
}
}
So my question is how can I get the data from id, in this case 26541044, and put that into a PHP variable?
Also to get the data from the JSON file, I have to search for the id while the array name 'viducius' came from a PHP variable.
TLDR:
The array $arrayName contains an id '26541044' that has to be saved into variable $id
Is there someone who can help me with this? I was thinking on doing this in jQuery but if it's easier with PHP only thats fine too.
That is a JSON String, therefore you need to convert it into a PHP data structure. PHP Provides json_decode() to do that.
$json_string = '{"viducius": {
"id": 26541044,
"name": "Viducius",
"profileIconId": 591,
"revisionDate": 1480517139000,
"summonerLevel": 30
}
}';
$obj = json_decode($json_string);
$id = $obj->viducius->id;
echo 'id = ' . $id;

Parsing Multidimensional Nested JSON with PHP

I feel like i am slightly insane, and I have certainly read the docs on this. I am completely unable to echo out various objects in a JSON array in PHP. I am not sure what I'm doing wrong, but I'm ripping my hair out...
Here is my JSON array:
{
"photos": {
"page": 1,
"pages": 1569045,
"perpage": 1,
"total": "1569045",
"photo": [
{
"id": "14842817422",
"owner": "23432140#N06",
"secret": "c37cfa1914",
"server": "3864",
"farm": 4,
"title": "pizza",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0
}
]
},
"stat": "ok"
}
I know this is simple, but I can't get it right. I would like to echo out four different values.
This is what I have been trying:
$photoId = $jsonDecoded['photos']['photo'][0]['id'];
$photoSecret = $jsonDecoded['photos']['photo'][0]['secret'];
$photoServer = $jsonDecoded['photos']['photo'][0]['server'];
$photoFarm = $jsonDecoded['photos']['photo'][0]['farm'];
I know this seems newbie. Please help...
Best,
The problem is that you have both objects and arrays in your json, but are using array syntax in your php.
There are two ways to fix this, 1st simply set the second parameter of json_decode to true:
json_decode($json, true);
This will create a multidimentional array you can access as suggested in your question, eg:
$photoId = $jsonDecoded['photos']['photo'][0]['id'];
Alertinitivly you can use object property syntax on your existing $jsonDecoded:
$photoId = $jsonDecoded->photos->photo[0]->id;
if there are multiple photo sub arrays then you can do like this.
//this will create array instead of object
$jsonDecoded = json_decode($your_feed_data,true);
foreach($jsonDecoded['photos']['photo'] as $sub_array){
$photoId = $sub_array['id'];
$photoSecret = $sub_array['secret'];
$photoServer = $sub_array['server'];
$photoFarm = $sub_array['farm'];
}

Trying to parse JSON with PHP

I'm new to php and this has really stumped me - i'm trying to parse this json in order to get the value of match_id.
{
"result": {
"status": 1,
"num_results": 1,
"total_results": 500,
"results_remaining": 499,
"matches": [
{
"match_id": 649218382,
"match_seq_num": 588750904,
"start_time": 1399560988,
"lobby_type": 0,
"players": [
{
"account_id": 4294967295,
"player_slot": 0,
"hero_id": 69
}
]
}
]
}
}
So far I have:
$matchhistoryjson = file_get_contents($apimatchhistoryurl);
$decodedmatchhistory = json_decode($matchhistoryjson, true);
$matchid = $decodedmatchhistory->{'match_id'};
But I'm pretty sure that's not the right way to do it at all. All I need out of this JSON file is the match id.
You are getting an array back from json_decode() as you passed the second parameter with a value of true so you access it like any multi-dimensional
array:
$matchhistoryjson = file_get_contents($apimatchhistoryurl);
$decodedmatchhistory = json_decode($matchhistoryjson, true);
echo $decodedmatchhistory['result']['matches'][0]['match_id'];
Demo
Naturally if you have multiple matches you wish to get the match ID for you can loop through $decodedmatchhistory['result']['matches'] and get them accordingly.
This is your code:
$matchhistoryjson = file_get_contents($apimatchhistoryurl);
$decodedmatchhistory = json_decode($matchhistoryjson, true);
$matchid = $decodedmatchhistory->{'match_id'};
Two issues. First when you set true in a call to json_decode() that returns the results as an array:
When TRUE, returned objects will be converted into associative arrays.
So you would access the data as an array like this:
$matchid = $decodedmatchhistory['match_id'];
But your original syntax is incorrect even if you were accessing the data as an object:
$matchid = $decodedmatchhistory->{'match_id'};
If you set json_decode() to false or even left that parameter out completely, you could do this instead:
$decodedmatchhistory = json_decode($matchhistoryjson);
$matchid = $decodedmatchhistory->match_id;
So try both out & see what happens.

Get JSON objects in PHP, not array

Im writing a website in php that gets a JSONstring from another php-api Ive created.
The string looks like this:
{
"result": "true",
"results": {
"20": {
"id": "20",
"desc": "a b ct tr",
"active": "1",
"startdate": "2013-04-03",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-03",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
},
"21": {
"id": "21",
"desc": "test",
"active": "0",
"startdate": "2013-04-04",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-04",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
}
}
}
Ive found lots of answers on how to get information from a JSONarray but Im not using an array here.
So the question is: how can I get the objects that are labeled 20, 21 and so forth(These numbers are generated by the server so I dont know which ones will be returned).
Or should I rewrite how my api returns the JSON as an array instead. Something like this:
{"result"="true", "results":[{...},{...},{...}]}
$json = json_decode($json_string, True);
foreach($json['results'] as $key => $value) {
// access the number with $key and the associated object with $value
echo 'Number: '.$key;
echo 'Startdate: '.$value['startdate'];
}
I suppose that you are getting the json by POST without any parameter, like
curl http://someapi.somedomain/someresource/ -X POST -d #data.json
so basically
$data = file_get_contents('php://input');
$object = json_decode($data);
print_r($object);
should solve your problem. and $object will be your json object that you post.
You do get the JSON response as a string. That's just the way JSON works. To "convert" the data to a format and structure that is easily accessible, you can use a PHP function called json_decode().
You have two choices when using the function -
To convert the data into an array. json_decode($jsonString,true)
If you use this method, you would access the data like you would for an associative array. $jsonArray['results']['21']
To convert the data into an object. json_decode($jsonString)
With this method, you would use object notation to traverse the data -
$num = 21;
$jsonObj->results->$num
First you decode the string($string) then you can loop through it and get all the properties of the objects. Remember that accessing properties is with ->prop instead of ['prop']. This way you do not have to deal with it in an array manner.
$jsoned = json_decode($string);
foreach($jsoned->results as $o) {
foreach($o as $key => $value) {
echo "The key is: ".$key." and the value is: ".$value."<br>";
}
}
Working example what will print out:
Key is: id and value is: 20
Key is: desc and value is: a b ct tr
Key is: active and value is: 1
etc...

Categories