I am new to php at this stage, same about openID libraries. I want to make a website for Steam users so I need to display their inventory. I've downloaded some example things which most thing written but I still need something else. As a training I took a something else than inventory, but similiar. Didn't make it so I hope that you can help me.
That's a example what I was looking at while trying to decode another data.
{
"response": {
"players": [
{
"steamid": "76hidden",
"communityvisibilitystate": 3,
"profilestate": 1
}
]
}
}
And code in PHP looks like
$url2 = file_get_contents("url");
$content = json_decode($url2, true);
$_SESSION['steam_steamid'] = $content['response']['players'][0]['steamid'];
$steamprofile['steamid'] = $_SESSION['steam_steamid'];
And this one above is working well. Could you please explain me why there is 0 between "steamid" and "players"? Also it looks like the session name matters, am I right? I was doing some tests and when I changed the name session it didn't work.
So here's what I am working on
JSON code:
{
"friendslist": {
"friends": [
{
"steamid": "765hidden",
"relationship": "friend",
"friend_since": 1428495026
},
{
"steamid": "764hidden",
"relationship": "friend",
"friend_since": 1355599210
},
{
"steamid": "764hidden",
"relationship": "friend",
"friend_since": 1423504205
},
much more friends
]
}
}
So I want to get the steamid and I got no idea how to get it. I've tried to get relationship as steamID is already used above:
$url3 = file_get_contents("url2");
$content2 = json_decode($url3, true);
$_SESSION['steam_relationship'] = $content2['friendslist']['friends'][0]['relationship'];
$steamfriends['friend'] = $_SESSION['steam_relationship'];
And of course echo $steamfriend['friend'] is not working. I see that person who made these PHP files already know what are the session names (if they need to be right to work). Any ideas where can I find it?
I feel really ashamed that I can't figure it myself.
Regards.
The first JSON
{
"response": {
"players": [
{
"communityvisibilitystate": 3,
"profilestate": 1,
"steamid": "76hidden"
}
]
}
}
translates to this PHP array
$content = array(
"response" => array(
"players" => array(
array(
"communityvisibilitystate" => 3,
"profilestate" => 1,
"steamid" => "76hidden"
)
)
)
)
The players is an array of arrays (hash arrays), so to access the first player you need to use index number ($content["response"]["players"][0]["steamid"]) even if there is just one player in the players array.
To get all steamids from the second array, you just need to run a simple foreach:
$friendIds = array();
foreach ($content2["friendslists"]["friends"] as $friend) {
$friendIds[] = $friend["steamid"];
}
# array("764hidden", "764hidden", "764hidden")
var_export($friendIds);
When the JSON is created they use a method similar to this:
foreach ($record as $response){
$content['response']['players'][] = $response;
}
Where $player may be an array with multiple values, or not.
It just makes it easier to create the JSON.
First make the JSON an array:
$array = json_decode($json,true)
Then get it like this:
session_start();
$_SESSION['relationship'] = $array['friendslist']['friends'][0]['relationship'];
$_SESSION['steamid'] = $array['friendslist']['friends'][0]['steamid'];
$_SESSION['steam_relationship'] = $array['friendslist']['friends'][0]['steam_relationship'];
The typical way to get all the player info:
foreach ($array['friendslist']['friends'] as $key => $value){
$steamid = $value['steamid'];
$relationship = $value['relationship'];
$friend_since = $value['friend_since'];
// do what need to be done here.
}
Related
I have the following json structure I am trying to loop through and extract products from:
[]JSON
->{0}
-->[]username
-->[]avatar
-->[]rep
-->[]products
-->[]groups
-->[]feedbacks
-->[]online
-->[]staff
I am trying to ave only the products object into as a JSON file. This is the only result I need and delete/unset the rest:
[]JSON
->{0}
-->[]products
But I seem to be a bit confused, as I am not to familiar with how arrays work around PHP. Here is an angle I am currently trying:
<?php
$str = file_get_contents('test.json');
$json_decoded = json_decode($str,true);
foreach($json_decoded as $index){
unset($json_decoded[$index][???]);
}
file_put_contents('cleaned.json', json_encode($json_decoded));
?>
I added ??? where I am lost, this is about as far as I have gotten. I keep getting super confused. I know the structure will always be the same as above so I can technically just remove username,avatar,rep,groups,feedbacks,online, and staff seperatly. Which is just fine.
Here is an example of the json structure:
[{"username":["1"],"avatar":["yellow"],"rep":["etc"],"products":["Big"],"groups":["small"],"feedbacks":["small"],"online":["small"],"staff":["small"]}]
Thank you in advance, even a push in the right direction is much appreciated.
You could compose a new products array like this :
$products = [];
foreach($json_data as $value) {
$products[]['products'] = $value['products'];
}
file_put_contents('cleaned.json', json_encode($products));
This will results json objects like this :
[
{
"products": ["Big-01"]
},
{
"products": ["Big-02"]
},
{
"products": ["Big-03"]
},
{
"products": ["Big-04"]
},
{
"products": ["Big-05"]
}
]
From your snippet. try this.
<?php
$str = '[{"username":["1"],"avatar":["yellow"],"rep":["etc"],"products":["Big"],"groups":["small"],"feedbacks":["small"],"online":["small"],"staff":["small"]}]';
$json_decoded = json_decode($str,true);
foreach($json_decoded as $value) {
$products = $value['products'];
}
print_r( $products);
?>
output
Array
(
[0] => Big
)
Create a new array ($products), iterate over the old array, and set products as the one property instead of unseting every single array.
$products = [];
foreach ($json_decoded as $index) {
$products[$index] = [
'products' => $json_decoded[$index]['products']
];
}
file_put_contents('cleaned.json', json_encode($products));
I'm sorry if I don't use the correct terminology, I'm still learning. I'm trying to figure out how to search a JSON array that has nested arrays in it for a specific value, and then return an associated value.
My problem is similar to this answered question on StackOverflow (How to search through a JSON Array in PHP), but I want to be able to find an item by id in either people or dog or any other nested array. Essentially I want to convert people below in the foreach to a wildcard.
Here is my JSON data - http://foothillertech.com/student/webdesign/2018/2018benrud2/tinker/dataIntro2/test/data.json
foreach($json->people as $item)
{
if($item->id == "8097")
{
echo $item->content;
}
}
Any help is greatly appreciated.
If id is unique in the data, you can merge the inner arrays and index them by id.
$data = json_decode($json, true);
$merged = array_merge(...array_values($data));
$indexed = array_column($merged, null, 'id');
Then you can look up any of the items by id.
echo $indexed['8097']['content'] ?? 'not found';
This only works if id is unique. If not, indexing by id will result in data loss.
In this case, simply do two loops.
$json = json_decode('{
"people": [
{
"id": "8080",
"content": "foo"
},
{
"id": "8097",
"content": "bar"
}
],
"dogs": [
{
"id": "8081",
"content": "spot"
},
{
"id": "8091",
"content": "max"
}
]
}');
foreach($json as $key=>$value){
//$key = people or dogs
//$value = stdClass()
foreach($value as $item)
{
if($item->id == "8097")
{
echo $item->content;
}
}
}
Output
bar
Sandbox
If we used 8081 instead of 8097 I would expect to get 'spot`. And testing that, I do indeed get that (which is in dogs).
I am wondering how to filter through a result like this properly. What I am doing results in problems. Obviously using a foreach on an array with a single item is not ideal but I don't know exactly how to do it any other way.
// connect with the static file
$json = file_get_contents('resources/assets/datafeeds/brewery_single.json');
$obj = json_decode($json, true);
// create brewery info
foreach($obj['pages'] as $brewery) {
foreach($brewery['results'] as $brewery) {
}
}
I've tried doing something like:
foreach($obj['pages']['results'] as $brewery) {
}
But I get an Undefined index: result errror like this.
Example data with only one result block, my data has multiple:
{
"apiName": "brewery_single",
"apiGuid": "d74e8aa2-4064-44b9-81de-2ceb150882c0",
"generatedAt": 1452761620,
"pages": [
{
"pageUrl": "http://www.brewery-website.com",
"results": [
{
"website": "www.brewery.com/",
"plaats": "Place",
"latlong": [
"53.657856",
"5.032597"
],
"naam": "Brouwerij title",
"provincie": "Noord Brabant",
"afbeelding": "http://www.brewery.com/images/brewery/brewer.jpg",
"actief": "Yes",
"land": "Netherlands",
"adres": "<p><b>Adres:</b><br />Street 40 <br />2388 GP<br /> Province, Netherlands </p>",
"opgericht": "1990"
}
]
},
]
}
Hopefully somebody can help me out so I can properly get my data from an api.
It seems like pages is an array of potentially multiple pages, each of which contains a results array of potentially multiple results. So indeed, two loops are in order:
foreach ($obj['pages'] as $page) {
foreach ($page['results'] as $brewery) {
...
}
}
If you're only ever interested in the first result, you can try to directly access it:
if (isset($obj['pages'][0]['results'][0])) {
echo $obj['pages'][0]['results'][0]['plaats'];
}
But again, the point of this data structure appears to be to account for multiple results, so you may be missing out on some information if you only ever consider the first.
Consult the documentation (which hopefully exists) of that API for exact details on the returned data.
Add an extra check to see if the data that you want is in the array:
if (isset($obj['pages'])) {
foreach($obj['pages'] as $brewery) {
if (isset($brewery['results'])) {
foreach($brewery['results'] as $brewery) {
}
}
}
}
There is syntax error in your code near ['results]
Change from
foreach($obj['pages']['results] as $brewery) {
into
foreach($obj['pages']['results'] as $brewery) {
There is no multiple arrays in results array. So why you need foreach there?
Anyways you can get value of results by providing exact INDEX.
For example: echo $obj['pages']['results]['website'];
I have a JSON file that, in essence, is structured like this:
[{
"name": "James",
"reviews": [
{
"stars": 5,
"body": "great!"
},
{
"stars": 1,
"body": "bad!"
}
]
},
{
"name": "David",
"reviews": [
{
"stars": 4,
"body": "pretty good!"
},
{
"stars": 2,
"body": "just ok..."
}
]
}]
Now when positing new review data for David to a PHP script, how do I target David's specific "reviews" and append it?
I have already decoded everything correctly and have access to both the decoded file and post information. I just don't know how to target David's specific reviews in the JSON array... Thank you in advance!
UPDATE - Just to be clear, everything is decoded already, the POST data and the JSON file from the server. I just need to know how to target David's reviews specifically and append it.
UPDATE 2 - Everyone, please also understand that this is in the case that the index is not known. Doing [1] would be awesome, but when someone submits, they won't know what index it is. The loop for the rendering is being done in AngularJS btw, so can't assign anything on the PHP side for the front-end.
You will have to make use of a for-loop/foreach to iterate through the array testing where arr['name'] === 'David',
then you can access arr['reviews'].
foreach ($array as $person)
{
if ($person['name'] === 'David')
{
$person['reviews'][] = array("stars"=> 3,"body"=> "pretty cool!");
break;
}
}
Edit:
You could also make a generic function for this
function findElem(arr,field,e)
{
foreach ($arr as $elem)
{
if ($elem[field] === e)
{
return $elem;
}
}
return null;
}
to call:
$elem = findElem(myArray,'name','David');
if ($elem !== null)
$elem[] = array("stars"=> 3,"body"=> "pretty cool!");
Looks like more work, but if you are going to do it repeatedly then this helps.
PHP >= 5.5.0 needed for array_column or see below for an alternate:
$array[array_search('David', array_column($array, 'name'))]['reviews'][] = array(
'stars'=>1,'body'=>'meh'
);
Instead of array_column you can use:
array_map(function($v) { return $v['name']; }, $array);
If you want specifically david's reviews, and only david's reviews... assuming that $array holds the json_decoded array:
$david_reviews = $array[1]["reviews"];
foreach($david_reviews as $review){
//Do code to retrieve indexes of array
$stars = $review["stars"] //5
$body = $review["body"] //Great!
}
If you're looking to grab reviews for each result, then user2225171's answer is what you're looking for.
json_decode($json, true) will return you the simple array of data. Then save what you need and save back with json_encode()
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'];
}