Parsing JSON keys and values in PHP - php

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>";
}
}
}

Related

Convert variable into array in php

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);
}
}
}
}
}

How to extract the JSON data from the nested arrays in PHP?

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'];

How to take a value from nested array(json format) without using multiple foreach in php

I want to take the all id values in the json format.
{
"1": {
"name": "test",
"followup": {
"1": {
"id": "98",
"followup": {
"1": {
"id": "93",
"followup": {
"1": {
"id": "174"
},
}
}
}
}
}
}
}
I can achieve this by using nested foreach. But now the 'followup' key is present in 3 but it may came 6,7 so we can't add 6,7 foreach.
You can use the array_walk_recursive() for this, like(DEMO):
$ids = array();
$data = json_decode($str, true);
array_walk_recursive($data, function($v, $k) use (&$ids) {
if ($k === 'id') {
$ids[] = $v;
}
});
var_dump($ids);
This basically goes through every index 1 at a time and matches the the keys against the key id, and if it matches it captures the value.

PHP get array items based on string mask

i have an array with a bunch of records like in:
{
"ID": "38424",
"heading": "Nylies soek nuwe hoof",
"typeID": "1",
"datein": "2016-09-26 12:14:16",
"edited_datein": null,
"publishDate": "2016-09-23 00:00:00",
"category": {
"ID": "1",
"heading": "News",
"typeID": "3",
"datein": "2016-09-26 11:50:06",
"edited_datein": null,
"url": "news"
},
"authorID": "592",
"tags": "skool,school,hoof,headmaster,etienne burger"
}
i have another array with "columns" i want the records to be "filtered" by
{
"ID",
"heading",
"datein",
"category|heading",
"category|url"
}
i would like the result to create a multidimensional array based on the column items:
{
"ID": "38424",
"heading": "Nylies soek nuwe hoof",
"datein": "2016-09-26 12:14:16",
"category": {
"heading": "News",
"url": "news"
}
}
how do i achieve this? i'm totally stuck on this now :( busy trying a hack of array_combine now but i dont hold much hope it would work out
so after being stuck on this for many hours.. and posting it here. i found a solution
$new_list = array();
foreach ($n as $record) {
$new_list[] = filter_columns($columns, $record);
}
and the function:
function filter_columns($columns, $record, $pre="") {
$return = array();
foreach ($record as $key => $value) { // loop through the fields in the record
$str = $pre.$key; // create a string of the current key
if (in_array($str,$columns)){
$return[$key] = $value;
}
if (is_array($value)){
$return[$key] = filter_columns($columns, $value,$key."|"); // if the value is an array recall the function but prepend the current key| to the key mask
}
}
return $return;
}

how to convert this malformed string to json with php/jquery

I have this string -
{
'Carlos':
{
Name: 'Spers',
href: "http://google.com"
},
'Winter':
{
Name: 'Warres',
href: "http://yahoo.com"
},
'Doer':
{
Name: 'Pinto',
href: "http://carpet.com"
}
}
I validated the with JSLinter, it say invalid with multiple errors. And I understand that. The issue is, this is what I get from a third party service. I have to leave with it. Now I'm stuck with it to convert into JSON object to work with it.
When I use json_decode($thisStirng) in PHP, it returns null. $.parseJSON(data) returns me errors too.
I would like to show the data on the webpage with some styling. So at the end, I want json object at the client to work with. So converting data to JSON with PHP or jQuery, anyway would work.
How should I go about it?
Update
I got an associative array with json_decode($thisStirng, true). Now I want echo it as a string so that on browser, I could access it with array indexes.
Thank you all - got it working as below -
$someObject = json_decode($thisStirng,true);
$myarry = array();
foreach ($someObject as $key => $val) {
$temparray = array();
$temparray[]= $key;
$temparray[]= $val;
$myarry[]= $temparray;
}
echo json_encode($myarry);
Now in jQuery I can access, data[index][0] as 'Carlos' and other dynamic keys. data[index][1] is an object with 'Name' and 'href' properies.
You can try this code.
$jsonData='{
"Carlos":
{
"Name": "Spers",
"href": "http://google.com"
},
"Winter":
{
"Name": "Warres",
"href": "http://yahoo.com"
},
"Doer":
{
"Name": "Pinto",
"href": "http://carpet.com"
}
}';
$arr1=array();
$arr2=array();
$arr3=array();
$phpArray = json_decode($jsonData, true);
foreach ($phpArray as $key => $value) {
$arr1=array();
$arr1[]=$key;
foreach ($value as $k => $v) {
$arr2=array();
$arr2[$k]=$v;
$arr3[]=$arr2;
}
}
echo $arr3[0]['Name'];
try using this:
<?php
$jsonData='{
"Carlos":
{
"Name": "Spers",
"href": "http://google.com"
},
"Winter":
{
"Name": "Warres",
"href": "http://yahoo.com"
},
"Doer":
{
"Name": "Pinto",
"href": "http://carpet.com"
}
}';
$phpArray = json_decode($jsonData, true);
foreach ($phpArray as $key => $value) {
echo "Key:".$key. ", Name:". $value['Name'].'<br>';
}
?>
OUTPUT:
Key:Carlos, Name:Spers
Key:Winter, Name:Warres
Key:Doer, Name:Pinto

Categories