How to correctly get info from JSON? - php

I use this to retrieve data from url in JSON:
$apiUrl = "https://api.uphold.com/v0/ticker/UPXAU";
$upxau_rates = file_get_contents($apiUrl);
if($upxau_rates !== false){
$upxau_rates_res = json_decode($upxau_rates);
}
foreach($upxau_rates_res as $upxau_rates_item)
{
if($upxau_rates_item->pair == "UPXAU-USD")
{
$usd_rate = $upxau_rates_item->ask;
}
}
JSON from api have this structure:
[{
"ask": "0.27226",
"bid": "0.27226",
"currency": "USD",
"pair": "AEDUSD"
},
{
"ask": "0.02675",
"bid": "0.02675",
"currency": "USD",
"pair": "ARSUSD"
},
{
"ask": "0.72624",
"bid": "0.72624",
"currency": "USD",
"pair": "AUDUSD"
},
...
So, this works fine. But I want to get information about 'ask rate' without 'foreach' and 'if'. For example:
$apiUrl = "https://api.uphold.com/v0/ticker/UPXAU";
$upxau_rates = file_get_contents($apiUrl);
if($upxau_rates !== false){
$upxau_rates_res = json_decode($main_currency);
}
echo $upxau_rates_res['pair']['UPXAU-USD']['ask'];
But this short way not work. How can I get info such short way?

Decode as an array and then index on pair to access it that way. To index all and access ask:
$array = json_decode($json, true);
echo array_column($array, null, 'pair')['AEDUSD']['ask'];
Or to just index the ask on pair:
echo array_column($array, 'ask', 'pair')['AEDUSD'];
To be able to use all of them:
$array = array_column($array, null, 'pair');
echo $array['AEDUSD']['ask'];

Related

how can filter json code

i have json file like below:
{
"data": [
{
"id": 8921,
"weather": null,
"status": "TT",
}, {"id": 8922,
"weather": null,
"status": "TF",
},
{
"id": 8923,
"weather": null,
"status": "NT",
}, {"id": 8922,
"weather": null,
"status": "HT",
}
]
}
i read this and show in table
but i want filter that with status and get just status have TF and size depend on.
old code without check status:
$jsonResult = file_get_contents('1.json');
$content_json = json_decode($jsonResult);
$size=sizeof($content_json->data);
the new code (did'nt work true):
$jsonResult = $jsonResult = file_get_contents('1.json');
$content_json = json_decode($jsonResult);
$content_json = array_filter($content_json['data'], function ($data) {
return $data['status'] != 'HT' or $data['status'] != 'NT';
});
You should iterate over the data array to check the status:
$jsonResult = file_get_contents('1.json');
$content_json = json_decode($jsonResult, true);
$data = $content_json['data'];
$filteredData = [];
foreach($data as $entry){
if($entry['status'] == "TF")
$filteredData[] = $entry;
}
$size = sizeof($filteredData);
Also, your JSON file has a syntax error, remove the commas after the status properties like so:
{
"data": [
{
"id": 8921,
"weather": null,
"status": "TT"
}, {"id": 8922,
"weather": null,
"status": "TF"
}
]
}
Using arrays as opposed to objects (pass true as the second parameter to json_decode()), you can use array_filter() to remove any elements your not interested in...
$content_json = json_decode($jsonResult,true);
$content_json = array_filter($content_json['data'], function ($data) {
return $data['status'] == 'TF';
});
echo count($content_json);
Update:
Your code should be...
$content_json = json_decode($jsonResult, true);
$content_json = array_filter($content_json['data'], function ($data) {
return $data['status'] != 'HT' and $data['status'] != 'NT';
});
Note the ,true on the json_decode() and the condition should be and not or.

Problems iterating through an array

I'm having problems looking through the array data from a json file.
This is the code I have
$barcode = '0000000' //just an example this is set as a variable
$json_data = json_decode($json,true);
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
if($barcodejson == $barcode){
$alreadyscanned = 'This user is already in your contacts';
} else { do something}
}
The problem I have is its only 'looking' at the last set of data and not all of it. if I put the barcode in twice I get the error This user is already in your contacts but if I put a new one in and then the existing barcode again it doesn't work.
I'm sure its something to do with the foreach loop but can not figure it out.
my json data is structured like this :
[
{
"FirstName": "lee",
"LastName": "skelding",
"Email": "mail.mail.com",
"Barcode": "732580652913857773001",
"Phone": "00000000",
"Company": "SKELLATECH V3",
"Position": "CEO"
},
{
"FirstName": "Kenneth",
"LastName": "Brandon",
"Email": "mail.mail.com",
"Barcode": "732559813913833509001",
"Phone": null,
"Company": null,
"Position": null
},
{
"FirstName": "lee",
"LastName": "skelding",
"Email": "mail.mail.com",
"Barcode": "732580652913857773001",
"Phone": "0000000000",
"Company": "SKELLATECH V3",
"Position": "CEO"
}
]
what I want to do is see if the barcode number already exists in the json file if it does show the error if it doesn't carry on with the rest of my code and add in the new data
For the second iteration, the $alreadyscanned will be set on a user that doesn't match the condition if one that has been scanned already came before it. Either reset the value of $alreadyscanned or use array to keep a list of errors.
$alreadyscanned = [];
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
if($barcodejson == $barcode){
$alreadyscanned[$barcodejson] = 'This user is already in your contacts';
} else { do something}
}
foreach($alreadyscanned as $barcode => $error) {
var_dump($barcode. " :: " . $error);
}
Consider using break in your loop when you get into the if part: you don't want to continue once you find a duplicate:
if($barcodejson == $barcode){
$alreadyscanned = 'This user is already in your contacts';
break;
} else { do something}
Now the dosomething could be unwanted here (depending on what it does). You may need to do that in a separate loop. Something like this:
$alreadyscanned= "";
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
if($barcodejson == $barcode){
$alreadyscanned = 'This user is already in your contacts';
break;
}
}
if ($alreadyscanned=="") {
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
// do something
}
}
Lacking semicolons and stuff makes it harder to get the desired result.
Something like this might help you out on getting the data you want. Basically you can check the result of parsing by print_r-ing the json decoding process.
Then, you get a process result for each entry and, again, as a test, you can print the resulting array.
<?php
//Enter your code here, enjoy!
$json = '[
{
"FirstName": "lee",
"LastName": "skelding",
"Email": "mail.mail.com",
"Barcode": "732580652913857773001",
"Phone": "00000000",
"Company": "SKELLATECH V3",
"Position": "CEO"
},
{
"FirstName": "Kenneth",
"LastName": "Brandon",
"Email": "mail.mail.com",
"Barcode": "732559813913833509001",
"Phone": null,
"Company": null,
"Position": null
},
{
"FirstName": "lee",
"LastName": "skelding",
"Email": "mail.mail.com",
"Barcode": "732580652913857773001",
"Phone": "0000000000",
"Company": "SKELLATECH V3",
"Position": "CEO"
}]'
;
$barcode = '732580652913857773001'; //just an example this is set as a variable
$json_data = json_decode($json, true);
print_r($json_data);
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
if($barcodejson == $barcode){
$alreadyscanned[] = 'user ' . $data["Email"] .' is already in your contacts';
} else {
$alreadyscanned[] = 'This user '. $data["Email"] .' is not in your contacts';
}
}
print_r($alreadyscanned);
You need to use a function for that, so that you can use return when you find the needed barcode
function searchbarcode($json_data, $barcode)
{
foreach($json_data as $data)
{
if ( $data['Barcode'] == $barcode )
return true;
}
return false;
}
$barcode = '0000000' //just an example this is set as a variable
$json_data = json_decode($json,true);
if(searchbarcode($json_data, $barcode)){
$alreadyscanned = 'This user is already in your contacts';
} else { do something}

Getting JSON data from website returns " string(0) "

I;m trying to get data from a website using the following code:
<?php
$url = 'http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=4798';
$content = file_get_contents($url);
var_dump($content);
$json = json_decode($content, true);
var_dump($json);
for ($idx = 0; $idx < count($json); $idx++) {
$obj = (Array)$json[$idx];
echo 'result' . $obj["name"];
}
?>
Which is getting me this result:
string(0) "" NULL
<?php
$url = 'http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=4798';
$content = file_get_contents($url);
echo "<pre>";
//print_r($content);
$data = json_decode($content);
print_r($data); //Show the json decoded data comes form $url
##Parse this array {$data} using foreach loop as your use
?>
There are no numeric keys in the json returned from the url you posted in your question. So iterating through the associative array with numeric keys returns nothing.
This is the structure of the json you are working with:
{
"item": {
"icon": "http://services.runescape.com/m=itemdb_oldschool/5122_obj_sprite.gif?id=4798",
"icon_large": "http://services.runescape.com/m=itemdb_oldschool/5122_obj_big.gif?id=4798",
"id": 4798,
"type": "Default",
"typeIcon": "http://www.runescape.com/img/categories/Default",
"name": "Adamant brutal",
"description": "Blunt adamantite arrow... ouch.",
"current": {
"trend": "neutral",
"price": 529
},
"today": {
"trend": "neutral",
"price": 0
},
"members": "true",
"day30": {
"trend": "negative",
"change": "-9.0%"
},
"day90": {
"trend": "negative",
"change": "-20.0%"
},
"day180": {
"trend": "negative",
"change": "-31.0%"
}
}
}
Try accessing $json["item"]. That should give you something more meaningful to work with. If you want to iterate over the key/value pairs in the item, use a foreach loop:
foreach($json["item"] as $key => $value) {
echo $key . ":";
print_r($value);
}

Get JSON value from array in PHP

I have the following JSON
[
{
"part_number": {
"id": "1",
"text": "962-00031-17A004"
},
"categoria": null,
"codigo_cti": "",
"fabricante": null,
"modelo": null,
"numero_serie": "",
"obs": ""
}
]
And I use the code bellow to collect data from it. If I select to extract obs, it works fine. I would like to know how can I collect the text and ID from part_number.
$produtos = json_decode($_POST['produtos'], true);
foreach($produtos as $produto){
echo $produto["obs"]; //WORKS FINE
echo $produto["part_number"]["text"]; //DOES NOT WORK
}
Turn it into an object and not array first - its easier and Object Orientated is the way to go.
Here is a working example;
$json = '[
{
"part_number": {
"id": "1",
"text": "962-00031-17A004"
},
"categoria": null,
"codigo_cti": "",
"fabricante": null,
"modelo": null,
"numero_serie": "",
"obs": ""
}
]';
$produtos = json_decode($json, false);
foreach($produtos as $produto){
echo $produto->part_number->id;
}

php decode JSON can't get a value inside an array

I'm trying to get thumbnail_url form the following JSON
{
"uuid": "00012710-4b65-0131-ffe6-22000a499ea4",
"camera_uuid": "98373a20-79ee-0130-3e42-1231390fcc11",
"created_at": "2013-12-20T05:25:02.000Z",
"percent_complete": 100,
"short_code": "KKtB4Q",
"metadata": {
},
"state": "published",
"recorded_from": "http://singwho.com",
"publish_type": null,
"formats": [
{
"name": "720p",
"width": 1280,
"height": 720,
"video_url": "https://cameratag.com/videos/00012710-4b65-0131-ffe6-22000a499ea4/720p/mp4.mp4",
"flv_url": null,
"flv_stream": null,
"mp4_url": "https://cameratag.com/videos/00012710-4b65-0131-ffe6-22000a499ea4/720p/mp4.mp4",
"mp4_stream": "rtmp://sa0xpxq1vz1ri.cloudfront.net/cfx/st&mp4:98373a20-79ee-0130-3e42-1231390fcc11/00012710-4b65-0131-ffe6-22000a499ea4_720p.mp4?Expires=1436913071&Signature=NppwMddejKbM2JMYrjsUUC5TJN0YfbgOox6sBKwO1YcftAaspf25ByG8drEG4zM-pTD6mST71YtBb3pQ5JzhHM33B6JQv0BsZvjGHarA7kVq9b6GG27wY5N5F6Sy79l5GNO3k9-Sh4MRy6fABZEDQUxd8TZ1HD7Usj2FlPYXxWXZmWQlo~43YKRnium7dcEzh-RRXbXfNQarfz1ju~OXI4J9ug1DRmHVtqV0F32cEDdCSCVy5Tyokf7IgO5SXATkuIkRtt52TdInFXmWmLbGfopDtKgua8NZXPaDbK35ra7AX2DuQE3iKTeX5oCWgVCPCAUz1PenLtK8rOYhTyYgJg__&Key-Pair-Id=APKAIYEVFIMHKY7YWGKA",
"webm_url": "https://cameratag.com/videos/00012710-4b65-0131-ffe6-22000a499ea4/720p/webm.webm",
"webm_stream": "rtmp://sa0xpxq1vz1ri.cloudfront.net/cfx/st&webm:98373a20-79ee-0130-3e42-1231390fcc11/00012710-4b65-0131-ffe6-22000a499ea4_720p.webm?Expires=1436913071&Signature=Qc-gjpwSHp3QmXzoiLuAMy11ReUHyLvRuuaszBYRT~GEzp~wl-TTZ-sGqo-XBlJlxH-54LmzXPryygS8ZCwdQQs0~5le69YXlL8RONl7kaLwmLSKlSE0PJlGzJoUW8kqO1mZxIfvrcmpYPdpCukm5J6eTv2U0rWCzAGfAeSiT7kUUc-9uGxLjjeOLIXVKebyYYhjT3wC-Gp5jd4ODCq3JB-IAWpOCOcXxF7oCuF-ag5WznaAeasW200M4yuYHvuDmu~dz~r52NcykeldzQ9Wq4laRuxaLRYaGZpB3y7og31RoWo75bomoT2vOO2rO-4~pz1tcfoYsg05T14er62KOA__&Key-Pair-Id=APKAIYEVFIMHKY7YWGKA",
"thumbnail_url": "https://cameratag.com/videos/00012710-4b65-0131-ffe6-22000a499ea4/720p/thumb.png",
"small_thumbnail_url": "https://cameratag.com/videos/00012710-4b65-0131-ffe6-22000a499ea4/720p/small_thumb.png",
"state": "COMPLETED",
"completed_at": "2013-12-20T05:30:12.000Z",
"length": 195
}
],
"plays": 0
}
This is how decode the JSON, I'm able to get 'uuid'
$raw = file_get_contents('php://input');
$json = json_decode($raw, true);
I tried with
foreach ($json->formats as $format) {
$url = $format["thumbnail_url"];
}
and
$url = $json->formats[0]->thumbnail_url
and
$url = $json['formats']['thumbnail_url']
but I'm still unnable to get the right value. I'm I missing something?
You just about had its $url = $json['formats'][0]['thumbnail_url']
$json is a nested array. $json['formats'] is an array of objects, to get the first object use $json['formats'][0]
You can easily see what is in $json with var_export($json) or print_r($json)

Categories