Trying to get the name of the latest Twitch-follower with help from a snipper I found online. However I get an error message which I can't understand
$json_array2 = json_decode(file_get_contents('https://api.twitch.tv/kraken/channels/'.strtolower($channelName).'/follows?limit=1'), true);
$latestFollower = $json_array2['follows']['user']['name'];
Typing in the URL in my broser I get this so I'm thinking follows->user->name should be right but I guess not :(
{
"follows": [
{
"created_at": "2014-07-09T23:30:59Z",
"_links": {
"self": "https://api.twitch.tv/kraken/users/username17376/follows/channels/sodapoppin"
},
"user": {
"_id": 65845277,
"name": "username17376",
"created_at": "2014-07-08T03:59:16Z",
"updated_at": "2014-07-08T04:14:14Z",
"_links": {
"self": "https://api.twitch.tv/kraken/users/username17376"
},
"display_name": "Username17376",
"logo": null,
"bio": null,
"type": "user"
}
}
],
"_total": 339627,
"_links": {
"self": "https://api.twitch.tv/kraken/channels/sodapoppin/follows?direction=DESC&limit=1&offset=0",
"next": "https://api.twitch.tv/kraken/channels/sodapoppin/follows?direction=DESC&limit=1&offset=1"
}
}
Should be
$json_array2['follows'][0]['user']['name'];
Based on your JSON
{
"follows": [
{
Which shows that follows is an array. The first object in the the array (index 0) is an object that has the property "user"
Related
The task is to fetch json user data from an api and store it in array. Then be able to make changes to it different routes.
Here is a sample of the data from the api, they are 10 in total and in an array.
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
i fetched the data using this:
$jsonurl = "http://jsonplaceholder.typicode.com/users";
$json = file_get_contents($jsonurl);
global $userData;
$userData = json_decode($json);
I displayed the data in a /users route with this
Route::get('/users', function(){
global $userData;
echo json_encode($userData);
});
I was told to get set a /delete route that deletes the last object from the array.
Route::get('/delete', function(){
global $userData;
$lastObjIndex = count($userData) -1;
array_splice($userData, $lastObjIndex,1);
//print_r('last user deleted');
echo json_encode($userData);
$userData = $userData;
});
The problem is that the delete route does not only works once(it does not delete subsequent last objects and returns the same thing when the route is accessed again) and does not show any change in when i access the users route. The data isn't stored in the server.
I feel there is something i don't know about that could help with this. Any suggestion would be appreciated.
I'm storing dynamic data in a MySQL JSON field using Laravel v6.11.0, nova v2.9.3 and nova-flexible-content v0.1.13. The data stored looks similar to this:
[
{
"layout": "source",
"key": "5ce8e0a877487fe5",
"attributes": {
"value": "342",
"unit": "USD",
"language": "en",
"url": "http:\\/\\/google.com",
"authority": "google.com",
"entry_date": "2020-01-21",
"date": "2019-12-21"
}
},
{
"layout": "source",
"key": "a82393ce016e8c14",
"attributes": {
"value": "444",
"unit": "USD",
"language": "en",
"entry_date": "2020-01-21",
"url": "https:\\/\\/google.com",
"authority": "TEST",
"date": "2020-01-20"
}
}
]
I was wondering if it's possible to build a Laravel Query to select the second entry based on the authority entry? Criteria are:
url should contain google.com AND
authority shouldn't be google.com
I've found https://laravel.com/docs/5.8/queries#json-where-clauses, but am struggling to put the right query together. Maybe someone could give me some pointers on how to do it? Thank you
You may refer to this discussion on Laracast
$data = App\YourModel::whereRaw('JSON_CONTAINS(body->"$[*].attributes.url", "\"https://google.com\"")')
->orWhereRaw('JSON_CONTAINS(body->"$[*].id", "\"http://google.com\"")')
->whereRaw('not JSON_CONTAINS(body->"$[*].attributes.authority", "\"google.com\"")')
->get();
foreach ($data as $key => $row) {
$bodyArr = json_decode($row->body);
foreach ($bodyArr as $item) {
if ((preg_match("/(http:\/\/www\.|https?:\/\/google.com)/i",$item->attributes->url)) && (strpos($item->attributes->authority, 'google.com') === false)) {
dump($item);
// YOUR CODE GOES HERE
}
}
}
Using PHP and Mongo I would like to update the users availability but cannot figure it out. How can I structure my collection to be able to reference availability groups.steve.availability?
Below is the structure of my "groups" collection:
{
"_id": {
"$oid": "524327d536b82c7c5c842f6d"
},
"group_id": "testing",
"password": "test",
"users": [
{
"username": "steve",
"availability": "null"
},
{
"username": "joeb",
"availability": "null"
}
]
}
If you want to reference it the way you've suggested: groups.steve.availability, you'd need to structure your documents more like below. (I'm not sure where groups is coming from).
This example would give you users.steve.availability by moving the user's name to a sub-field of the users field (users.steve).
{
"_id": {
"$oid": "524327d536b82c7c5c842f6d"
},
"group_id": "testing",
"password": "test",
"users": {
"steve": {
"availability": "null"
},
"joeb" : {
"availability": "null"
}
}
}
Or, you could just create fields directly on the document:
{
"_id": {
"$oid": "524327d536b82c7c5c842f6d"
},
"group_id": "testing",
"password": "test",
"steve": {
"availability": "null"
},
"joeb" : {
"availability": "null"
}
}
That would allow you to just use steve.availability.
If you're trying to do a query though, you'd be better off leaving it more like you had it originally:
"users": [
{
"username": "steve",
"availability": "null"
}]
So, you could write queries that were like:
db.groups.find({"users.username" : "steve" })
Ok, so that title might be a little misleading, but I'm not quite sure what i'm describing, so here goes.
I have the following JSON :
{
"lastModified": 1368517749000,
"name": "Requiem Paradisum",
"realm": "Chamber of Aspects",
"battlegroup": "Misery",
"level": 25,
"side": 1,
"achievementPoints": 1710,
"emblem": {
"icon": 126,
"iconColor": "ffdfa55a",
"border": 3,
"borderColor": "ff0f1415",
"backgroundColor": "ff232323"
},
"news": [
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368482100000,
"itemId": 91781
},
{
"type": "itemLoot",
"character": "Greenmean",
"timestamp": 1368477900000,
"itemId": 87209
},
{
"type": "itemLoot",
"character": "Greenmean",
"timestamp": 1368475800000,
"itemId": 86880
},
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368475380000,
"itemId": 91781
},
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368475380000,
"itemId": 91779
},
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368475320000,
"itemId": 91779
},
{
"type": "playerAchievement",
"character": "Osmoses",
"timestamp": 1368470700000,
"achievement": {
"id": 6193,
"title": "Level 90",
"points": 10,
"description": "Reach level 90.",
"rewardItems": [
{
"id": 87764,
"name": "Serpent's Heart Firework",
"icon": "inv_misc_missilelarge_green",
"quality": 1,
"itemLevel": 1,
"tooltipParams": {
},
"stats": [
],
"armor": 0
}
],
"icon": "achievement_level_90",
"criteria": [
],
"accountWide": false,
"factionId": 2
}
},
Basically i need to loop over everything in "news" and output it.
What I can't figure out how to parse it correctly :
A : without specifying key numbers and
B : when it gets to a key that then contains further keys and further arrays under those keys i'm at a loss. (E.g. the "player achievement" key)
I appreciate I'm probably being a bit newbie here and could quite possibly be on page 1 of "php for dummies" but i swear I've googled it to death!
See if this approach could fit. Be sure your JSON array is properly formatted though.
$test = the_json_array;
$array = json_decode($test,true);
function recursive($array) {
foreach($array as $key => $value) {
if (!is_array($value)) echo $key.":".$value."<br/>";
else recursive($value);
}
}
recursive($array);
SEE json_decode
Dont forget to give second argument as TRUE otherwise it will return object
and try something like this
$json = 'your json'
$json_array = json_decode($json,true);
$news = $json_array['news'];
foreach($news as $value)
{
print_r($value);
}
I think for your purpose you should have look at array_walk_recursive
function printResult($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($news, 'printResult');
yo need to do json_decode('your-jason', True) it will convert your Json string to Array.
Json_decode for more understanding
if you don't specify TRUE in jason_decode function then it will return php object
Hope answer the question. regards
I want to make a PHP JSON data foreach, but I met some problem. First: I can not get the properties part. Second it alawys show wrong in line: echo '<div class="image">...
Fatal error: Cannot use object of type stdClass as array in ...
This is the json data:
[
{
"post_id": "504464716_189878284371815",
"message": "\"Happy Birthday to You\" \"Happy Birthday to Mama\"",
"attachment": {
"media": [
{
"href": "http:\/\/www.facebook.com\/photo.php?fbid=493710409716&set=a.453260184716.254996.504464716",
"alt": "",
"type": "photo",
"src": "http:\/\/photos-f.ak.fbcdn.net\/hphotos-ak-snc4\/hs049.snc4\/34793_493710409716_504464716_5821684_2056840_s.jpg",
"photo": {
"aid": "2166659457206182932",
"pid": "2166659457211749620",
"owner": 504464716,
"index": 24,
"width": 225,
"height": 225
}
}
],
"name": "Wall Photos",
"href": "http:\/\/www.facebook.com\/album.php?aid=254996&id=504464716",
"caption": "\"Happy Birthday to You\" \"Happy Birthday to Mama\"",
"description": "",
"properties": [
{
"name": "By",
"text": "Suman Acharya",
"href": "http:\/\/www.facebook.com\/profile.php?id=504464716"
}
],
"icon": "http:\/\/static.ak.fbcdn.net\/rsrc.php\/yD\/r\/aS8ecmYRys0.gif",
"fb_object_type": "album",
"fb_object_id": "2166659457206182932"
},
"action_links": null,
"privacy": {
"value": ""
}
},
...
]
Here is my php code:
foreach ($data as $result) {
echo '<div class="title">'.htmlspecialchars($result->message).'<br />'.htmlspecialchars($result->description).'<br />'.htmlspecialchars($result->caption).'<br />';
if(!empty($result->attachment->properties[0]->text)){
foreach ($result->attachment->properties[0] as $properties) {
echo htmlspecialchars($properties->name).'<br />'.htmlspecialchars($properties->text).'</div>';
}
}
if(!empty($result->attachment->media)){
echo '<div class="image"><img src="'.htmlspecialchars($result->attachment->media[0]->src).'" /><br>'.htmlspecialchars($result->attachment->media[0]->type).'</div>';
}
}
If i were you i would just force the decoding to an assoc array by true as the second arg to json_decode. If you cant or dont want to do that then try accessing it like this:
$result->attachment->media->{0}->href
Use json_decode($the_data, true); instead of json_decode($the_data); that way it will return you an associative array instead of a StdClass.