Modify JSON Feed With php - php

I have a JSON Feed which is accessed by an api.
The json feed it returns is as below:
[
{
"isoDate":"2017-09-15T00:00:00.0000000",
"events":[
{
"id":"-7317",
"name":"Exhibition SKMU: The collection 2015-2017",
},
{
"id":"-91417",
"name":"Torget - a multi cultural meeting place in Geilo",
}
]
},
{
"isoDate":"2017-09-16T00:00:00.0000000",
"events":[
{
"id":"-7317",
"name":"Exhibition SKMU: The collection 2015-2017",
},
{
"id":"-91417",
"name":"Torget - a multi cultural meeting place in Geilo",
}
]
}
]
I need the isoDate to be listed with each event instead of individually.
e.g.
[
{
"events":[
{
"isoDate":"2017-09-15T00:00:00.0000000",
"id":"-7317",
"name":"Exhibition SKMU: The collection 2015-2017",
},
{
"isoDate":"2017-09-15T00:00:00.0000000",
"id":"-91417",
"name":"Torget - a multi cultural meeting place in Geilo",
}
]
},
{
"events":[
{
"isoDate":"2017-09-16T00:00:00.0000000",
"id":"-7317",
"name":"Exhibition SKMU: The collection 2015-2017",
},
{
"isoDate":"2017-09-16T00:00:00.0000000",
"id":"-91417",
"name":"Torget - a multi cultural meeting place in Geilo",
}
]
}
]
Can this be achieved with php? Basically fetch that feed from a url and then display it in my preferred format?

So this is what you have to do, to get back your desired format of the json,
$json is your json string:
$eventList = json_decode($json);
foreach($eventList as $eventEntry){
$isoDate = $eventEntry->isoDate;
foreach($eventEntry->events as $subEventEntry){
$subEventEntry->isoDate = $isoDate;
}
//delete the isoDate from outer
unset($eventEntry->isoDate);
}
echo json_encode($eventList);
So basically, you are first decoding your json into php structure, apply your changes and after that, encode it back. Note here, that I have not appened true as second parameter for the $json_decode, but working with the resulting object.
Also: Your json is not standard comform and could result in errors. PHP will properly not decode it, because your object end with a comma. The last element of an object should be without comma. Instead of
{
"id":"-91417",
"name":"Torget - a multi cultural meeting place in Geilo",
}
make it like this:
{
"id":"-91417",
"name":"Torget - a multi cultural meeting place in Geilo"
}
I know, this can be a problem, when you get it from an API, but this is another problem of itself...
EDIT:
To get every "events" into one big array, you have to store them just like your imagination ;) . Think it like this: $subEventEntry holds one "events"-object. Because you are iterating both levels, you see everyone object of them. My suggestion would be to store them in a new array, and recreating the structure around it:
$everything = new stdClass();
$everything->events = array();
and then, in the inner loop:
foreach($eventList as $eventEntry){
$isoDate = $eventEntry->isoDate;
foreach($eventEntry->events as $subEventEntry){
$subEventEntry->isoDate = $isoDate;
$everything->events[] = $subEventEntry; // <-- this has to be added
}
//delete the isoDate from outer
unset($eventEntry->isoDate);
}
When recreating the structure, and you don't need the old structure anymore you could remove the unset.
Just remeber every [ ] pair in the json represents an array, every { } pair an object (stdClass). The name of this object/array is referenced -> by its class property in the superobject.

Yes you can using json_decode() function for example:
$yourjson;/* your json */
$events = json_decode($yourjson, true);
foreach($events as $event){
echo $event["isoDate"];
}

You can use json_decode to decode the json object to php array then modify the array and encode it using json_encode

Related

Split Json object into multiple json objects in PHP

I'm a newbie to PHP and I want to split a json object that I have stored in a variable into multiple json objects.
My input looks like this :
{
"results":[
{
"id":"001",
"items":{
"item11":"value1",
"item12":"value2",
"item13":"value3"
},
{
"id":"002",
"items":{
"item21":"value1",
"item22":"value2",
"item23":"value3"
},
{
"id":"003",
"items":{
"item31":"value1",
"item32":"value2",
"item33":"value3"
}]
}
I want to first extract each id and store it into a variable and associate to each id the correspondant json that will look like this :
$id1 = "001";
{
"item11":"value1",
"item12":"value2",
"item13":"value3"
}
Try this loop over each record and save it in result.
$json=json_decode($str,true);
array_map(function($value) use (&$results){
$results[$value['id']]=json_encode($value['items']);
return $results;
}
,$json['results']);
print_r($results);
output
Array (
[001] => {"item11":"value1","item12":"value2","item13":"value3"}
[002] => {"item21":"value1","item22":"value2","item23":"value3"}
[003] => {"item31":"value1","item32":"value2","item33":"value3"} )
if you want to display every array item in results, you can use extract($arr['results'])
but if you want to have specific name you should use loops to do it, depend on your pattren

Navigating through api response in php

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.

Extract particular array from multidimensional array

I have a JSON array of data that I am trying to extract particular value/keys(?) from, and would like to add them into a new array.
The array looks like this:
{ "total':2000,
"achievements":[
{
"id":6,
"achievement":{},
"criteria":{
"id":2050,
"is_completed":false
},
"completed_timestamp":1224053510000
},
{
"id":8,
"achievement":{},
"criteria":{
"id":1289,
"is_completed":true
},
"completed_timestamp":0000000
}
]
}
I want to search for true in the is_completed, and then add the id from that array into a new array.
Basically, find the id's of all the key/array (sorry unsure of terminology) where is_completed is true.
I've tried something simple like finding trying to find the key of an ID, but struggling to get that to work. And also seen some of the multi-level for loop examples but can't get them to work for my data.
Example:
$key = array_search('1289', array_column($array, 'id'));
As pointed out in the comments, you could combine array_filter (to filter completed events) and array_column (to extract their IDs).
$completedAchievements = array_filter(
$array->achievements,
static function (\stdClass $achievement): bool {
return $achievement->criteria->is_completed === true;
}
);
$completedAchievementsIds = array_column($completedAchievements, 'id');
print_r($completedAchievementsIds); // Array([0] => 8)
Note: the code above supposes your JSON was decoded as an object. If it was decoded as an array, just replace -> syntax with the corresponding array index access.
Demo

laravel - trying to remove item from fetched collection

I need to remove items from a collection based on an attribute (Laravel 5.6).
$leagues = League::all();
foreach($leagues as $i => $L){
if($L->status == LeagueStatus::HIDDEN){
$leagues->forget($i); <<<<======== 1st attempt
unset($leagues[$i]); <<<<======== 2nd attempt
}
}
return response()->json($leagues->toArray());
Both methods removes the items correctly, but causes that response JSON comes as object:
{ <<<<======== ITS OBJECT WITH NUMBERED KEYS, NOT ARRAY
"0":{
"id":1,
"title":"test...
Correct JSON would be:
[ <<<<======== NORMAL ARRAY WITH OBJECTS
{
"id":1,
"title":"test...
Am I doing something wrong?
Use values to get a new Collection with the keys reset to consecutive integers:
return response()->json($leagues->values());
Laravel 6.x Docs - Collections - Available Methods - values
Just replace this
return response()->json($leagues->toArray());
to
return json_decode($leagues);

php json_decode not returning any results

i am trying to figure out why i am not returning any data when i use json_decode. i'm trying to get values that are in a valid json file (yes, i tested it). when i try and use:
foreach($json['designs']['filters'] as $filters) {
echo $filters['filterTypeName'];
}
i am returning the values ... that's great, but i am trying to get down to the next level of the json file to pull just the values for each array under "values". here is the json file results from file_get_contents('url'):
{"designs": {
"filters" :
[
{
"filterTypeName":"Year",
"filterProperty":"year",
"values":
[
{
"name":"2018",
"value":"2018",
"sortvalue":"1"
},
{
"name":"2017",
"value":"2017",
"sortvalue":"2"
}, (etc.)
]
},
{
"filterTypeName":"Division",
"filterProperty":"division",
"values":
[
{
"name":"Resort-Apparel",
"value":"Resort-Apparel",
"sortvalue":"1"
},
{
"name":"College-Apparel",
"value":"College-Apparel",
"sortvalue":"2"
}, (etc.)
]
}, (etc.)
essentially, i have a select options on my form that checking against the values listed above to return designs that match the criteria.
how do i specifically search for all of the years in one select group, then all of the divisions in another select group and so-on?
thanks for any and all of your help!!
Try using $json->designs-> filters for accessing filters instead of $json['designs']['filters']
As the others have said, json_decode returns an object unless true is specified as the second parameters, so your options are either:
Use $json->designs->filters
or use json_decode($json, true)
i used foreach($json['designs']['filters'][0]['values'] as $name) i forgot to specify the number of the array i was trying to access.

Categories