So I am pulling the API from Coinmarketcap.com and the new version has a really different data structure.
Also I am a newb at PHP and APIs really don't understand how to pull the nested array data out of the api call.
Here is the api data:
https://api.coinmarketcap.com/v2/ticker/1/
or
https://api.coinmarketcap.com/v2/ticker/1/?structure=array
{
"data": [
{
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"website_slug": "bitcoin",
"rank": 1,
"circulating_supply": 17148000.0,
"total_supply": 17148000.0,
"max_supply": 21000000.0,
"quotes": {
"USD": {
"price": 6233.51,
"volume_24h": 3674820000.0,
"market_cap": 106892229480.0,
"percent_change_1h": -0.11,
"percent_change_24h": -0.46,
"percent_change_7d": -6.25
}
},
"last_updated": 1531544203
}
],
"metadata": {
"timestamp": 1531543852,
"error": null
}
}
What I decided to do is pull the object into json_dcode and then loop through it creating a new array each time until I was able to grab the array data i wanted, which in this case was $a(). This worked, but I thought there might be a more efficient way of doing this as i think the for-loops will cause performance issues. Is there a better way to do this? thank you in advance. -Dan
Here is my test code please show me a better way:
<?php
$BitcoinContents = file_get_contents("https://api.coinmarketcap.com/v2/ticker/1/?structure=array");
$BTCContents = json_decode($BitcoinContents, true);
echo " 0 <br>";
print_r($BTCContents);
echo "<br>";
foreach($BTCContents as $array){
echo "<br>--------<br>";
print_r($array);
foreach($array as $arr){
echo "<br>--------<br>";
print_r($arr);
foreach($arr as $ar){
echo "<br>--------<br>";
print_r($ar);
foreach($ar as $a){
echo "<br>--------<br>";
print_r($a);
foreach($a as $key => $val){
echo "<br>=========<br>";
echo "$key: $val | ";
}
}
}
}
}
echo "<br>=========<br>";
echo "<br>--------<br>";
print_r($a);
echo "<br>--------<br>";
echo "<br>=========<br>";
echo "<br>".$a['price']."<br>";
echo "<br>--------<br>";
echo "<br>=========<br>";
?>
If your are trying to access a particular array in a nested array, just do this:
$data = $BTCContents['data'][0]['quotes']['USD'];
Here I have used the index of the arrays to access a specific array which is USD.
Index of array = Name of the array which can be a word or digit.
Then you can do a foreach loop to access the item inside or you can access them directly by doing:
$price = $data['price'];
Related
When I use <pre>to display my variable echo $value_detail_final;
it displays a proper file like this
{
"companies": [
{
"id": "4127303000000527195",
"company_name": "235 St Georges Landowning Trust & Australian City Properties Pty Ltd"
},
{
"id": "4127303000004495043",
"company_name": "Bourke Junction No 1 Pty Ltd"
},
{
"id": "4127303000000527189",
"company_name": "Brookfield Commercial Operations Pty Ltd"
}
]
}
But when I use something like this $value_detail_final[0] it displays {
if $value_detail_final[1] its ", its like displaying each character on my variable .
even foreach doesnt work, by the way this is from json file and I use json_decode file.
How can I able to put each of the id and company_name into a variable so I can use them ?
This is how I decode my json file based on the given sturcture
$jsondata = file_get_contents("response.json");
$array = json_decode($jsondata,true);
echo "<pre>";
foreach ($array as $key => $value) {
// echo "Key:".$key."<br>";
if($key=='details')
{
foreach ($value as $key_detail => $detail)
{
if($key_detail=='userMessage')
{
foreach ($detail as $key_detail_final => $value_detail_final)
{
print_r($value_detail_final);
}
}
}
}
}
These are the values in JSON
"_id": "5db81ae803f7410018f7c081",
"hotness": 72793.81406699134,
"activityHotness": 0.10295588022415446,
"primaryCategory": "Exchanges",
"words": 443,
"similarArticles": [],
"coins": [
{
"_id": "59cb59e81c073f09e76f614b",
"name": "Bitcoin",
"slug": "bitcoin",
"tradingSymbol": "btc"
},
{
"_id": "59d21e9b83a0523906a45dc5",
"name": "EOS",
"slug": "eos",
"tradingSymbol": "eos"
},
{
"_id": "59d21e9b83a0523906a45dbe",
"name": "Tether",
"slug": "tether",
"tradingSymbol": "usdt"
}
],
"description": "The world’s 5th largest crypto exchange OKEx is planning to launch Tether futures trading, offering a linear futures contract with leverage of up to 100x.\nThe world’s 5th largest crypto exchange OKEx is planning to launch Tether ( USDT ) futures trading, offering a linear futures contract with…",
"publishedAt": "2019-10-29T10:16:00.000Z",
"title": "OKEx to Launch USDT Futures Trading With Up to 100x Leverage",
"url": "https://cryptocontrol.io/r/api/article/5db81ae803f7410018f7c081?ref=5d9f090e03f7410018f41938",
"source": {
"_id": "59d70be3ef8bf95cc2aa2b4f",
"name": "CoinTelegraph",
"url": "https://cointelegraph.com/",
"favicon": "https://assets.cryptocontrol.io/favicons/59d70be3ef8bf95cc2aa2b4f.png"
},
"sourceDomain": "cointelegraph.com",
"originalImageUrl": "https://images.cointelegraph.com/images/740_IGh0dHBzOi8vczMuY29pbnRlbGVncmFwaC5jb20vc3RvcmFnZS91cGxvYWRzL3ZpZXcvMWY5YTllNWViMGI1NTNhMWJkNWVlYjBhZWNkOTAxYzkuanBn.jpg"
},
I want to truncate the values from Id to coins and display the values starting from description
I am trying to get keys and values from the JSON file in Blockchain array. But I want to truncate some of them. Not getting idea how to do.
I have tried using foreach loop
<?php
$getJsonData = file_get_contents("sample.json");
$jsonArray = json_decode($getJsonData);
$mainName = "blockchain";
$i = 1;
foreach($jsonArray->$mainName as $row){
echo "<br>----------record $i start <br><br>";
foreach($row as $key => $val){
if(is_object($val)){
foreach($val as $ky => $v1){
echo $key.' => '.$ky.': '.$v1;
echo '<br>';
}
}else{
echo $key.': '.$val;
echo '<br>';
}
}
echo "<br>----- record $i end <br><br>";
$i++;
}
?>
Since you call json_decode() without the optional second argument, the JSON objects are decoded as PHP objects, not associative arrays. So you can't use foreach() to loop over the object properties.
Use json_decode($getJsonData, true) and then all the objects will become associative arrays.
Then you can use array_keys() to get all the keys, and remove all the keys between _id and coins.
$keys = array_keys($jsonArray[$mainName][0]);
$id_index = array_search('_id', $keys);
$coins_index = array_search('coins', $keys);
array_splice($keys, $id_index, $coins_index - $id_index + 1); // remove keys from _id to coins
foreach ($jsonArray[$mainName] as $row) {
foreach ($keys as $key) {
$val = $row[$key];
if (is_array($val)) {
foreach ($val as $k => $v) {
echo "$key => $k: $v<br>";
}
} else {
echo "$key: $val<br>";
}
}
}
I'm using this code $json_output = (json_decode($json, true)); to transform from JSON to an associative array in PHP.
The resulting array looks too compĺex to me, I need to print only some keys and values but they are nested and so far I haven't been able to do it, the examples I had follow for printing are too basic for this.
This is part of my JSON:
{
"project": {
"company": "Company Name SA de CV",
"name": "Project Name",
"files": [
{
"project-id": "666666",
"filenameOnDisk": "HH-ORG-CMD-GUI-File.docx",
"uploaded-date": "2018-01-29T21:20:56Z",
"private": "0",
"version-id": "3939061",
"status": "active",
"tags": [
{
"name": "OPD",
"id": "25047",
"color": "#9e6957"
}
],
"id": "3796128",
"last-changed-on": "2018-01-29T21:21:46Z",
"versions": [],
"uploaded-by-user-first-name": "Someone",
"uploaded-by-user-last-name": "Anything",
"name": "HH-ORG-CMD-GUI-GUIA_RAPIDA_PARA_CREAR_PROCESOS",
"size": "262747",
"category-name": "Instructivos"
},
{
"project-id": "666",
etc...,
},
When parsed looks like
How do I print (lets say) filenameOnDisk and id keys of the Files array.
I don't know how to get to that nested array.
echo $json_output['project']['files'][0]['project-id'];
echo $json_output['project']['files'][0]['filenameOnDisk'];
echo $json_output['project']['files'][0]['version-id'];
Or you could put it in a foreach loop using an array of values you want (as long as they're all in the 'files' array). Eg.
$wantedValues = array("project-id","filenameOnDisk","version-id");
foreach ($wantedValues as $value) {
echo $json_output['project']['files'][0][$value];
}
I Just needed to add a couple of lines at the code provided by #SeeSamRun in order to get the full "Files" array.
$filesArray = $json_output['project']['files'];
$filesSize = count($filesArray);
$wantedValues = array("project-id","filenameOnDisk","version-id");
for ($i=0; $i < $filesSize; $i++) {
foreach ($wantedValues as $value) {
echo $json_output['project']['files'][$i][$value];
}
}
I can do a var_dump, but when trying to access the values, I am getting errors about the values not being found.
{
"metrics": {
"timers": [
{
"name": "com.android.timer.launchtime",
"startTime": 1232138988989,
"duration_ms": 1900
},
{
"name": "com.android.timer.preroll-load-time",
"startTime": 1232138988989,
"duration_ms": 1000
}
]
}
}
I used the following so far to try and parse it.
$json_file = file_get_contents('test.json');
$json_a = json_decode($json_file,true);
var_dump(json_decode($json_file)); //This works
echo $json_a['name']; //I want to print the name of each (from timers).
Try:
$yourDecodedJSON = json_decode($yourJson)
echo $yourDecodedJSON->metrics->timers[0]->name;
Or you can:
$yourDecodedJSON = json_decode($yourJson, true); // forces array
echo $yourDecodedJSON['metrics']['timers'][0]->name;
In your case, you may want to..
foreach($yourDecodedJSON['metrics']['timers'] as $timer){
echo $timer['name']; echo $timer['duration_ms']; // etc
}
If something fails, use:
echo json_last_error_msg()
To troubleshoot further
You need do it in following manner:-
<?php
$data = '{
"metrics": {
"timers": [
{
"name": "com.android.timer.launchtime",
"startTime": 1232138988989,
"duration_ms": 1900
},
{
"name": "com.android.timer.preroll-load-time",
"startTime": 1232138988989,
"duration_ms": 1000
}
]
}
}';
$new_array = json_decode($data); //convert json data into array
echo "<pre/>";print_r($new_array); //print array
foreach ($new_array->metrics->timers as $new_arr){ // iterate through array
echo $new_arr->name.'<br/>'; // rest you can do also same
}
?>
Output:- https://eval.in/407418
I have a PHP page where I reference a JSON object that looks like this:
{
"body": {
"zip": "02110",
"stores": [
{
"storeEmail": "email#email.com",
"storeName": "Name",
"city": "City",
"Availability": {
"123": {
"Quote": "daily",
"Display": "available",
}
},
},
Each JSON object contains multiple "stores", above is one example.
I can currently echo the store name by using this:
echo "<br>".$phpArray->body->stores{0}->storeName;
How do I echo the value "123" from the sample JSON? I would also like to echo the quote as a separate variable. The value "123" will change for different searches. Any help would be greatly appreciated!
$phpArray = json_decode($json, true);
foreach($phpArray['body']['stores'] as $store) {
echo $store['storeName'];
foreach{$store['Availabilty'] as $avail => $info) {
echo $avail; // 123
echo $info['Quote'];
}
}
$b = json_decode($a);
var_dump(key($b->body->stores{0}->Availability));
var_dump(reset($b->body->stores{0}->Availability)->Quote);
or a loop for stores
foreach($b->body->stores as $store) {
var_dump(key($store->Availability));
var_dump(reset($store->Availability)->Quote);
}