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"
Related
i'm trying to get the fields "name, price, image and rarity" to show in a php file, anyone can help me? Thanks ;D
{
"status": 300,
"data": {
"date": "2019-09-16T00:00:00.000Z",
"featured": [
{
"name": "Flying Saucer",
"price": "1,200",
"images": {
"icon": icon.png",
},
"rarity": "epic",
},
I'm using this that a friend told me, but i cant put that to work :c
<?php
$response = json_decode(file_get_contents('lista.json'), true);
foreach ($response as $val) {
$item = $val['name'];
echo "<b>$item</b>";
}
?>
I'm not quite sure what you are trying to achieve. You can just access the contents via the $response array like this:
echo $response['status']; // would output 300
You can use foreach to iterate through the array. For example: If you want to output the name of every element of the array you can use:
foreach ($response['data'] as $val) { // loop through every element of the data-array (if this makes sense depends on the structure of the json file, cant tell because it's not complete)
echo $val['featured']['name'];
}
You gotta get the index in $val['data']['featured']['name'] to retrieve the name index.
When you defined the second parameter of json_decode, you said that you want your json to be parsed to an array. The brackets in the original json identify when a new index of your parsed array will begin.
I suggest you to read about json_decode and json in general:
JSON: https://www.json.org/
json_decode function: https://www.php.net/manual/en/function.json-decode.php
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 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 have a php code that reads JSON files. Part of the JSON sample below:
"Main": [{
"count": 7,
"coordinates": [89,77],
"description": "Office",
},{
"count": 8,
"coordinates": [123,111],
"description": "Warehouse",
}]
and I am trying to code PHP to only get the info (count, coordinates, description) of those who's description is included in the criteria like Warehouse. PHP Sample below
$validcriteria = array("Warehouse", "Parking_lot");
How do I do an if-statement to check first if "description" is included in the valid criteria. I tried the code below but it doesn't seem to work right.
$JSONFile = json_decode($uploadedJSONFile, false);
foreach ($JSONFile as $key => $value)
{
if (in_array($key['description'] , $validcriteria))
{
#more codes here
}
}
My code in PHP has been working except when I try to add $key['description'] to try and check the description first if it's valid. My code above is reconstructed to remove sensitive information but I hope you got some idea of what I was trying to do.
When attempting to understand the structure of a parsed JSON string, start with a print_r($JSONFile); to examine its contents. In your case, you will find that there is an outer key 'Main' which holds an array of sub-arrays. You will need to iterate over that outer array.
// Set $assoc to TRUE rather than FALSE
// otherwise, you'll get an object back
$JSONFile = json_decode($uploadedJSONFile, TRUE);
foreach ($JSONFile['Main'] as $value)
{
// The sub-array $value is where to look for the 'description' key
if (in_array($value['description'], $validcriteria))
{
// Do what you need to with it...
}
}
Note: if you prefer to continue setting the $assoc parameter to false in json_decode(), examine the structure to understand how the objects lay out, and use the -> operator instead of array keys.
$JSONFile = json_decode($uploadedJSONFile, FALSE);
foreach ($JSONFile->Main as $value)
{
// The sub-array $value is where to look for the 'description' key
if (in_array($value->description, $validcriteria))
{
// Do what you need to with it...
}
}
You might also consider using array_filter() to do the test:
$included_subarrays = array_filter($JSONFile['Main'], function($a) use ($validcriteria) {
return in_array($a['description'], $validcriteria);
});
// $included_subarrays is now an array of only those from the JSON structure
// which were in $validcriteria
Given your JSON structure, you probably want
foreach($decoded_json['Main'] as $sub_array) {
if (in_array($sub_array['description'], $validation)) {
... it's there ...
}
}
Because you set false to second argument of json_decode function, it's returned as an object,
if you change it to TRUE, the code would work.
http://php.net/manual/en/function.json-decode.php
and you have to change key to value;
foreach ($JSONFile->Main as $key => $value)
{
if (in_array($value->description, $validcriteria))
{
#more codes here
}
}
this code assume your json file has one more depth greater than your example. that's why $JSONFile->Main in the foreach loop.
Try to use that :
if ( array_key_exists('description', $key) )
I'm trying to pull the price from the following JSON but can't seem to figure out how to reference the actual values:
{"cards": [ { "high": "0.73", "volume": 1, "percent_change": "-2.67", "name": "Lightning Bolt", "url": "http://blacklotusproject.com/cards/Revised+Edition/Lightning+Bolt/", "price": "0.73", "set_code": "3ED", "average": "0.73", "change": "-0.02", "low": "0.73"}], "currency": "USD" }
So far I've got this code, which gets into the cards array but I'm unsure how to get farther - every attempt I've tried returns null.
$json = file_get_contents($url); $data = json_decode($json, TRUE);
echo var_dump($data[cards]);
Can someone shed light on what I need to do?
$data['cards'] has another array within it. You will need to access this array with index 0. For instance, $data['cards'][0]['high'] and so on.
$data['cards'] is an array itself, so you could do:
foreach ($data['cards'] AS $carditem) {
echo $carditem['high'];
...
}
to get all items in that array,
or if you only want the first item $data['cards'][0]['...']
To access using a string literal array index, always use quotes.
$data["cards"]
Link: PHP Documentation for Arrays