Search a value in JSON using PHP - php

<?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.

Related

How to get a specific value from a json array out of a list of arrays

everyone, I was just trying to find out a way to get the value of a link from a JSON array , after I have searched the array with help of Id. I am using PHP's file_get_contents and the webpage from which information is to be taken looks like
[{
"id":"2972",
"name": "AbC",
"link":"any link",
"epg": "any link",
"dur": "disabled",
"language": "y",
"category": "TOP 100",
"logo": "any url here"
},
{
"id": "1858",
"name": "Efg",
"link": "url",
"epg": "url",
"dvr": "disabled",
"language": "E",
"category": "TOP 100",
"logo": "url"
}]
From here suppose I have been given an Id 1858 so I have to find a link from the array of Id having 1858
I am a beginner in PHP and was just fidgeting around with a piece of code and tried to get its solution and a big Thanks To You For Your Answer and valuable Time.
if you are using file_get_contents('php://input'); then you should try this to access json data
$json = file_get_contents('php://input'); //get json data in variable
$array = json_decode($json); //parse json data in php array
// assecc the array with use of foreach loop
foreach($array as $obj){
//access the json element here like $id = $obj->id; $url = $obj->link;
//if you want to check the id value in array you can compare value with if condition
$id = $obj->id;
// find link for specific id
if($id =='1858'){
$url = $obj->link;
echo $url; // do something with link
//you can use break; statement if you found your element and terminate the loop
}
}
You can use array_column, to map pairs of json keys/values:
<?php
$json ='
[
{
"id": 3,
"link": "http:\/\/example.com\/3"
},
{
"id": 5,
"link": "http:\/\/example.com\/5"
}
]';
$data = json_decode($json, true);
if($data !== null) {
echo array_column($data, 'link', 'id')[5] ?? null;
}
Output:
http://example.com/5
To understand this we can see the result of array_column.
var_export(array_column($data, 'link', 'id'));
Output:
array (
3 => 'http://example.com/3',
5 => 'http://example.com/5',
)
So with the above code, we are checking for and outputting the associated index of 5 (the original id).

How to search through nested JSON arrays in 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).

Parse/traverse JSON with PHP

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"

Get JSON objects in PHP, not array

Im writing a website in php that gets a JSONstring from another php-api Ive created.
The string looks like this:
{
"result": "true",
"results": {
"20": {
"id": "20",
"desc": "a b ct tr",
"active": "1",
"startdate": "2013-04-03",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-03",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
},
"21": {
"id": "21",
"desc": "test",
"active": "0",
"startdate": "2013-04-04",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-04",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
}
}
}
Ive found lots of answers on how to get information from a JSONarray but Im not using an array here.
So the question is: how can I get the objects that are labeled 20, 21 and so forth(These numbers are generated by the server so I dont know which ones will be returned).
Or should I rewrite how my api returns the JSON as an array instead. Something like this:
{"result"="true", "results":[{...},{...},{...}]}
$json = json_decode($json_string, True);
foreach($json['results'] as $key => $value) {
// access the number with $key and the associated object with $value
echo 'Number: '.$key;
echo 'Startdate: '.$value['startdate'];
}
I suppose that you are getting the json by POST without any parameter, like
curl http://someapi.somedomain/someresource/ -X POST -d #data.json
so basically
$data = file_get_contents('php://input');
$object = json_decode($data);
print_r($object);
should solve your problem. and $object will be your json object that you post.
You do get the JSON response as a string. That's just the way JSON works. To "convert" the data to a format and structure that is easily accessible, you can use a PHP function called json_decode().
You have two choices when using the function -
To convert the data into an array. json_decode($jsonString,true)
If you use this method, you would access the data like you would for an associative array. $jsonArray['results']['21']
To convert the data into an object. json_decode($jsonString)
With this method, you would use object notation to traverse the data -
$num = 21;
$jsonObj->results->$num
First you decode the string($string) then you can loop through it and get all the properties of the objects. Remember that accessing properties is with ->prop instead of ['prop']. This way you do not have to deal with it in an array manner.
$jsoned = json_decode($string);
foreach($jsoned->results as $o) {
foreach($o as $key => $value) {
echo "The key is: ".$key." and the value is: ".$value."<br>";
}
}
Working example what will print out:
Key is: id and value is: 20
Key is: desc and value is: a b ct tr
Key is: active and value is: 1
etc...

Proper way to push values to an array PHP?

I have run into a problem that is a little irritating. Here is my PHP code. Ignore where the variables are coming from. This is for shopping-cart functionality but it is applicable in many different areas.
$data_set = json_decode(stripslashes($_POST['varA']), true);
$pid = $pid['product_id'];
$quantity = $pid['quantity'];
$_SESSION['cartid'] = $_SESSION['cartid'] + 1;
$product_data = array("Product_ID" = > $pid, "quantity" = > $quantity, "cartid" = > $_SESSION['cartid']);
My issue is occurring at this place in the code. I first check to see if the Session variable has a value in it, if not then it proceeds to create an associative array.
if (empty($_SESSION['cart_items'])) {
$_SESSION['cart_items'] = array("items" = > $product_data);
} else {
array_push($_SESSION['cart_items']['items'], $product_data);
}
echo json_encode($_SESSION['cart_items']);
The end result after the first item is "added" looks like this:
{
"items": {
"Product_ID": "2",
"quantity": "1",
"cartid": 1
}
}
However, after several the first add, every value gets a key:
{
"items": {
"0": {
"Product_ID": "2",
"quantity": "1",
"cartid": 2
},
"1": {
"Product_ID": "2",
"quantity": "1",
"cartid": 3
},
"Product_ID": "2",
"quantity": "1",
"cartid": 1
}
}
How do I prevent these keys from occuring? Is this possible? If not, how can this be re-written so that the keys are added every time? And is this possible to parse and loop through in JS on the front end?
Sorry I have so many questions. Any help is really appreciated.
In the first iteration, the $_SESSION['cart_items'] is empty, so you run this:
$_SESSION['cart_items'] = array("items" => $product_data);
This creates $_SESSION['cart_items']['items'] but you populate it with just the product by itself; you should define it as an array instead:
$_SESSION['cart_items'] = array("items" => array($product_data));
This creates an array with a single item which you can later extend with array_push.
Having said that, you can replace the whole condition with just:
$_SESSION['cart_items']['items'][] = $product_date;
PHP will automatically create an empty array if it didn't exist yet, followed by adding the product data as the next element.
This is because of this line:
$_SESSION['cart_items'] = array("items" = > $product_data);
You essentially say in that line that 'items' key has product data, instead of key in items. It should be:
$_SESSION['cart_items']['items'] = array($product_data);
Keys -will- always occur, unless you want data to overwrite another. If you do not want keys (0,1 etc) then the only other option is merging data. In which case it would be:
$_SESSION['cart_items']['items']+=$product_data;
..but I don't think that is what you want.
You don't need the items, try the below way.
if (empty($_SESSION['cart_items'])) {
$_SESSION['cart_items'] = array($product_data);
} else {
$_SESSION['cart_items'][] = $product_data;
}

Categories