Convert variable into array in php - 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);
}
}
}
}
}

Related

how to search inside two JSON files at a time in PHP

I have two JSON files of same format, forexample
1st JSON File
{
"data": {
"business": {
"id": "3NzA0ZDli",
"customers": {
"pageInfo": {
"currentPage": 1,
"totalPages": 695,
"totalCount": 1389
},
"edges": [
{
"node": {
"id": "QnVzaW5lc3M6Z",
"name": "Joe Biden",
"email": "joe#mail.com"
}
},
{
"node": {
"id": "QnVzaW5lc3M6Z",
"name": "MULTIMEDIA PLUMBUM",
"email": "mdi#mail.com"
}
}
]
}
}
}
}
2nd JSON file
{
"data": {
"business": {
"id": "3NzA0ZDli",
"customers": {
"pageInfo": {
"currentPage": 2,
"totalPages": 695,
"totalCount": 1389
},
"edges": [
{
"node": {
"id": "QnVzaW7dQ8N",
"name": "Mark",
"email": "mark#mail.com"
}
},
{
"node": {
"id": "QnVzaW5l5Gy9",
"name": "Trump",
"email": "trump#mail.com"
}
}
]
}
}
}
}
Each user has a unique "id", I want to get their id by searching their name in php, how can I do this
This is my PHP script
$json1 = file_get_contents("1.json");
$json2 = file_get_contents("2.json");
$result1 = json_decode($json1, true);
$result2 = json_decode($json2, true);
foreach ($result2 as $k => $v) {
if ($v['data']['business']['edges']['customers']['node']['name'] == "Trump") break;
}
echo $result[$k]['data']['business']['edges']['customers']['node']['name']; //I want to get id for trump "QnVzaW5l5Gy9"
Each user has a unique "id", I want to get their id by searching their name in php. How can I get id by searching name in both files at a time?
Thanks
Since you are looping through json file it will search inside of "data" so you can't use $v['data']
Also since edges is also array that have same values and you want to search inside of it you must make loop on that also
Here is example
foreach ($result2 as $k => $v) {
foreach ($v['business']['customers']['edges'] as $val) {
if ($val['node']['name'] == 'Trump') {
echo '<pre>';
// and now you can access any of those values, echo $val['node']['id'];
print_r($val['node']);
echo '</pre>';
}
}
}
Output
Array
(
[id] => QnVzaW5l5Gy9
[name] => Trump
[email] => trump#mail.com
)
EDIT
Since you want to search in both files at a same time you can put them into array and then use it like this
$json1 = file_get_contents("1.json");
$json2 = file_get_contents("2.json");
$result1 = json_decode($json1, true);
$result2 = json_decode($json2, true);
$joined_result = array($result1, $result2);
foreach($joined_result as $val) {
// this will take all nodes where you will search
$node = $val['data']['business']['customers']['edges'];
foreach ($node as $value) {
if ($value['node']['name'] == 'Trump') {
echo '<pre>';
print_r($value['node']);
echo '</pre>';
}
}
}
You have two questions there, no?
The first question I get is "How to get the ID for a certain name"
$node = $result2['data']['business']['customers']['edges']['node'];
if ($node['name'] == "Trump") echo $node['id'];
Almost your code, but I echo the ID when the name matches "Trump".
The second question I see is "How do search both json data at once"
$json1 = file_get_contents("1.json");
$json2 = file_get_contents("2.json");
$result1 = json_decode($json1, true);
$result2 = json_decode($json2, true);
$all_data = [$result1, $result2];
foreach($all_data as $data) {
$node = $data['data']['business']['customers']['edges']['node'];
if ($node['name'] == "Trump") echo $node['id'];
}
Transforming both json data to be in an array and then simply looping over the whole array should do the trick.

Parsing JSON keys and values in 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>";
}
}
}

Decode nested JSON PHP

I want to get the data such as domain name, dns, ip address of a website and I have found the following JSON structure that can help me to do so.
But I am getting errors in parsing particular information such as dns_records->type , dns_records->target etc.
Here is my nested JSON code:
{
"meta": {
"code": 200,
"time": 1477428559,
"requestId": "1f1d72299d7138924196681ca628a699"
},
"data": {
"tutorialspoint.com": {
"updated_datetime": "2015-08-17 13:56:03",
"domain_status": "[\"clientDeleteProhibited http:\\/\\/www.icann.org\\/epp#clientDeleteProhibited\",\"clientRenewProhibited http:\\/\\/www.icann.org\\/epp#clientRenewProhibited\",\"clientTransferProhibited http:\\/\\/www.icann.org\\/epp#clientTransferProhibited\",\"clientUpdateProhibited http:\\/\\/www.icann.org\\/epp#clientUpdateProhibited\"]",
"full_whois": "Domain Name: TUTORIALSPOINT.COM",
"dns_records": "[{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"A\",\"ip\":\"66.135.33.172\"},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"NS\",\"target\":\"ns44.domaincontrol.com\"},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"NS\",\"target\":\"ns43.domaincontrol.com\"},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"SOA\",\"mname\":\"ns43.domaincontrol.com\",\"rname\":\"dns.jomax.net\",\"serial\":2015080700,\"refresh\":28800,\"retry\":7200,\"expire\":604800,\"minimum-ttl\":3600},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"MX\",\"pri\":1,\"target\":\"ASPMX.L.GOOGLE.com\"},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"MX\",\"pri\":5,\"target\":\"ALT1.ASPMX.L.GOOGLE.com\"},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"MX\",\"pri\":5,\"target\":\"ALT2.ASPMX.L.GOOGLE.com\"},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"MX\",\"pri\":10,\"target\":\"ALT3.ASPMX.L.GOOGLE.com\"},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"MX\",\"pri\":10,\"target\":\"ALT4.ASPMX.L.GOOGLE.com\"},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"TXT\",\"txt\":\"v=spf1 mx include:_spf.google.com -all\",\"entries\":[\"v=spf1 mx include:_spf.google.com -all\"]},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"TXT\",\"txt\":\"google-site-verification=-RNr-P1jBNMarh7tMQEgXtlBVUi000DUph-h8H7uSaQ\",\"entries\":[\"google-site-verification=-RNr-P1jBNMarh7tMQEgXtlBVUi000DUph-h8H7uSaQ\"]}]",
"owner_email": null,
"registrar": "GODADDY.COM, LLC",
"registrar_slug": "godaddy.com-llc",
"hosted_ip": "66.135.33.172",
"hosted_ip_latitude": "29.4997",
"hosted_ip_longitude": "-98.3992",
"hosted_ip_country": "US",
"hosted_ip_friendly_location": "Texas, San Antonio, United States, 78218",
"hosted_ip_full_country": "United States"
}
}
}
How do I find the dns_records->type and dns_records->target from the above code?
dns_records contain more type and target so you can access all types and targets this way,
$record = '{
"meta": {
"code": 200,
"time": 1477428559,
"requestId": "1f1d72299d7138924196681ca628a699"
},
"data": {
"tutorialspoint.com": {
"updated_datetime": "2015-08-17 13:56:03",
"domain_status": "[\"clientDeleteProhibited http:\\/\\/www.icann.org\\/epp#clientDeleteProhibited\",\"clientRenewProhibited http:\\/\\/www.icann.org\\/epp#clientRenewProhibited\",\"clientTransferProhibited http:\\/\\/www.icann.org\\/epp#clientTransferProhibited\",\"clientUpdateProhibited http:\\/\\/www.icann.org\\/epp#clientUpdateProhibited\"]",
"full_whois": "Domain Name: TUTORIALSPOINT.COM",
"dns_records": "[{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"A\",\"ip\":\"66.135.33.172\"},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"NS\",\"target\":\"ns44.domaincontrol.com\"},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"NS\",\"target\":\"ns43.domaincontrol.com\"},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"SOA\",\"mname\":\"ns43.domaincontrol.com\",\"rname\":\"dns.jomax.net\",\"serial\":2015080700,\"refresh\":28800,\"retry\":7200,\"expire\":604800,\"minimum-ttl\":3600},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"MX\",\"pri\":1,\"target\":\"ASPMX.L.GOOGLE.com\"},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"MX\",\"pri\":5,\"target\":\"ALT1.ASPMX.L.GOOGLE.com\"},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"MX\",\"pri\":5,\"target\":\"ALT2.ASPMX.L.GOOGLE.com\"},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"MX\",\"pri\":10,\"target\":\"ALT3.ASPMX.L.GOOGLE.com\"},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"MX\",\"pri\":10,\"target\":\"ALT4.ASPMX.L.GOOGLE.com\"},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"TXT\",\"txt\":\"v=spf1 mx include:_spf.google.com -all\",\"entries\":[\"v=spf1 mx include:_spf.google.com -all\"]},{\"host\":\"tutorialspoint.com\",\"class\":\"IN\",\"ttl\":3599,\"type\":\"TXT\",\"txt\":\"google-site-verification=-RNr-P1jBNMarh7tMQEgXtlBVUi000DUph-h8H7uSaQ\",\"entries\":[\"google-site-verification=-RNr-P1jBNMarh7tMQEgXtlBVUi000DUph-h8H7uSaQ\"]}]",
"owner_email": null,
"registrar": "GODADDY.COM, LLC",
"registrar_slug": "godaddy.com-llc",
"hosted_ip": "66.135.33.172",
"hosted_ip_latitude": "29.4997",
"hosted_ip_longitude": "-98.3992",
"hosted_ip_country": "US",
"hosted_ip_friendly_location": "Texas, San Antonio, United States, 78218",
"hosted_ip_full_country": "United States"
}
}
}';
$record = json_decode($record, true);
$dnsRecords = json_decode($record['data']['tutorialspoint.com']['dns_records'], true);
$typeArray = array();
$targetArray = array();
foreach($dnsRecords as $row){
foreach($row as $key=>$res){
if($key == 'type'){
$typeArray[] = $res;
}
if($key == 'target'){
$targetArray[] = $res;
}
}
}
I created two arrays for targets and types, you can access each target and type this way,
// targets
foreach($targetArray as $target){
echo $target;
}
// types
foreach($typeArray as $type){
echo $type;
}
I think you need something like this:
$final_array= json_decode($array)
foreach ($final_arrayas $key => $value) {
if ($key == 'data') {
foreach ($value as $key2 => $val) {
foreach($val as $key3=> $child_array_val){
if($key3=='dns_records') echo "<pre>";
print_r($child_array_val);}
}
}
}

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

Decoding a JSON object and echo a specific value?

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

Categories