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).
Related
<?php
$str = '[
{
"node":{
"id": "bitcoin",
"name": "Bitcoin",
"price_usd": "610.471"
}
},
{
"node":{
"id": "ethereum",
"name": "Ethereum",
"price_usd": "12.0771"
}
}
]';
$result = json_decode($str, true);
$key = array_search('bitcoin', array_column($result,'node','id'));
echo $result[$key]['price_usd']; // i need 610.471 here
?>
I have a long json code like above, I need to get the "price_usd" value by searching "id" name.
i dont want $str[0]["node"]["price_usd"]
Just iterate over the array and break when you get a hit:
foreach ($result as $k => $v) {
if ($v['node']['id'] == 'bitcoin') break;
}
echo $result[$k]['node']['price_usd'];
The above code assumes that each sub-array has a key called node which also contains a key called id. If you can't rely on those things you need to check on each iteration. I also assume you only need one value (the first one) since there could easily be multiple instances of id being equal to bitcoin
You can use a double array_column() in order to get the list of prices by id:
$prices_by_id = array_column(array_column($result, 'node'), 'price_usd', 'id');
This is needed because of the multiple nested levels in the original JSON string.
The value of $prices_by_id:
array(2) {
["bitcoin"]=>
string(7) "610.471"
["ethereum"]=>
string(7) "12.0771"
}
This way you can use $prices_by_id['bitcoin'] to get its price.
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'];
After parsing this JSON in PHP, how can I access a particular value without using a foreach ?
[
{
"currency": "CAD",
"exchange": "1"
},
{
"currency": "EUR",
"exchange": "0.7158"
},
{
"currency": "GBP",
"exchange": "0.5131"
},
{
"currency": "MXN",
"exchange": "12.4601"
},
{
"currency": "USD",
"exchange": "0.8122"
}
]
Is it possible to make like this ?
$string = file_get_contents("datas.json");
$json = json_decode($string, true);
$json['currency']['USD']['exchange'];
Thanks a lot for your help.
You have an array of objects defined there but because you used the TRUE option on the json_decode they will get converted to an array of arrays so you would need to address them as
$string = file_get_contents("datas.json");
$json = json_decode($string, true);
echo $json[0]['currency']; // CAD
echo $json[0]['exchange']; // 1
If you want to use the currency name as a key you will have to change the data structure of the json data file.
You can use array_search() if you don't want to see foreach within your code.
$key = array_search("USD", array_column($json, "currency"));
echo $json[$key]['exchange'];
But one way or another, to find an exact value, you need to iterate over the array to have an exact match.
The first index in the data you get from json_decode() is numeric, starting from zero. If you intend to directly access the part where GBP is mentioned, you have to iterate over it, you cannot do it directly.
You have to do it at least once in order to create a data structure that is better suited to your needs and avoid iterating more than once.
I was thinking about whether or not it would possible to stuff the data inside an intelligent object that would try to avoid iterating, but I didn't come to an obvious solution. You'd have to explain why iterating at least once would not do what you want, or why it has drawbacks you cannot afford. That example data set of five currencies doesn't look too bad, and I think there are at most 200 currencies in the world. Performance and memory shouldn't be of a big issue here.
how about this?
$json = json_decode($string, true);
$currency = array();
foreach($json as $arr) {
foreach($arr as $key => $value) {
$currency[$key] = $value;
}
}
echo $currency['USD']; // echoes "0.8122"
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.
}
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()