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
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);
}
}
}
}
}
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.
This question already has answers here:
Get data from JSON file with PHP [duplicate]
(3 answers)
Closed 6 years ago.
I want print specific vars from array inside a document.
JSON structure:
{
"return": {
"string": "2222",
"contacts": [
{
"contact": {
"id": "09890423890"
}
},
{
"contact": {
"id": "2423444"
}
},
{
"contact": {
"id": "24242423"
}
},
etc
]
}
}
I am trying to do this in PHP (and already decoded that json). How can I access and print all ids using foreach or for?
I can not understand how I can manage "return" scope.
You can decode the json contents and use it like an array. This should work:
$json = json_decode($string, true);
$contacts = $json['return']['contacts'];
foreach($contacts as $contact){
echo $contact['contact']['id'];
}
Json decode to array:
$json = json_decode($strjson, true); // decode the JSON into an associative array
and
echo "<pre>";
print_r($json);
And foreach:
foreach ($json as $key => $value) {
echo $key . " ". $value. "<br>";
}
Working example:
$json = '{
"return": {
"string": "2222",
"contacts": [
{
"contact": {
"id": "09890423890"
}
},
{
"contact": {
"id": "2423444"
}
},
{
"contact": {
"id": "24242423"
}
}
]
}
}';
$json = json_decode($json, true);
print_r($json);
foreach ($json['return']['contacts'] as $val) {
echo $val['contact']['id']."<br>";
}
Try this code:
$json ='
{
"return": {
"string": "2222",
"contacts": [
{
"contact": {
"id": "09890423890"
}
},
{
"contact": {
"id": "2423444"
}
},
{
"contact": {
"id": "24242423"
}
},
etc
]
}
}
';
$array = json_decode($json,TRUE);
foreach($array['return']['contacts'] as $value ){
echo $value['id'];
}
Use file_get_contents function if you want to pull data from file.
json after json_encoded
{
"data":[
{
"name":"JIN",
"id":"100007934492797"
},
{
"name":"aris",
"id":"100008128873664"
},
{
"name":"Madm",
"id":"34234234"
}
],
"paging":{
"next":"https://graph.facebook.com/v1.0/1380314981/friends?limit=5000&offset=5000&__after_id=enc_AeyRMdHJrW0kW9vIZ41uFPXMPgE-VwRaHtQJz2JWyVc0hMl9eOG10C6JWjoCO8O2E4m24EPr28gIt9mxQR8oIQmN"
}
}
I want to store the name and ID of my json in db. But when I use for loop there's a problem with the offset, I suspect it's the last part of the json. How to remove the paging part? I tried
foreach($friends as friend){
echo friend[0]->name;
}
First, your original code would never work:
foreach($friends as friend){
echo friend[0]->name;
}
Those references to friend should have $ in front of them making them $friend. Then to solve your larger issue, just use a nested foreach loop:
$json = <<<EOT
{
"data": [
{
"name": "JIN",
"id": "100007934492797"
},
{
"name": "aris",
"id": "100008128873664"
},
{
"name": "Madm",
"id": "34234234"
}
],
"paging": {
"next": "https://graph.facebook.com/v1.0/1380314981/friends?limit=5000&offset=5000&__after_id=enc_AeyRMdHJrW0kW9vIZ41uFPXMPgE-VwRaHtQJz2JWyVc0hMl9eOG10C6JWjoCO8O2E4m24EPr28gIt9mxQR8oIQmN"
}
}
EOT;
$friends = json_decode($json);
foreach($friends as $friend_data){
foreach($friend_data as $friend){
echo $friend->name . '<br />';
}
}
And the output of this would be:
JIN
aris
Madm
Additionally, if working with arrays makes more sense for you, you can always set json_decode to return an array by setting the second parameter to true. Here is refactored code as an example:
$friends = json_decode($json, true);
foreach($friends as $friend_data){
foreach($friend_data as $friend_key => $friend_value){
if (isset($friend_value['name'])) {
echo $friend_value['name'] . '<br />';
}
}
}
i try to read json by php
{
"data": [
{
"id": "3043252fsdgdf36360354",
"name": "name1",
"access_token": "CAAIf3VEtVSoBAHrVxHL16zt4H5OvwBmdfgs4F3auPE0NZBx5PmIujBAdqw0Cv4bZACXytT1O1y6FHEZA25E1aqQZD"
},
{
"id": "3326848fdgsdfgsdf03424168",
"name": "name2",
"access_token": "CAAIf3VEtVSoBAJinePVdfgsdfgMxuY3zaj9AimaoKx7VIO9jCqZCHC6ZBixL1n6ZC72LTMn0ZB4T8rOHD27WmzbBVgvUwgspeEZD"
}}
i try by this code
$sfgsdfg= $json_a=json_decode($read,true);
echo $json_a['data'][3043252fsdgdf36360354];
echo $json_a['3043252fsdgdf36360354'][access_token];
not working with this php code i need help to read it
i need select access_token by 3043252fsdgdf36360354 as echo $json_a['data'][3043252fsdgdf36360354]['access_token'];
i need only read by id as . mysql command . select access_token where id ='3326848fdgsdfgsdf03424168';
First of all, your JSON is missing a ] character and will cause json_decode to return NULL. You should first correct the JSON string. You can use a online service such as jsonlint.com to validate the JSON. Once you've decoded the JSON string as an associative array, you can just loop through the array and check if it contains the given ID in it. If it does, you can grab the corresponding access token easily.
I've made this into a short little function. You can use that to get the access token by ID:
$jsonArray = json_decode($str, TRUE);
function getAccessTokenFromID($id, $jsonArray) {
foreach ($jsonArray['data'] as $k => $elem) {
if($elem['id'] == $id) {
$access_token = $elem['access_token'];
}
}
return $access_token;
}
Usage:
$myid = '3043252fsdgdf36360354';
$my_accesstoken = getAccessTokenFromID($myid, $jsonArray);
Demo!
Isn't well formed json.
Try with:
{
"data": [
{
"id": "3043252fsdgdf36360354",
"name": "name1",
"access_token": "CAAIf3VEtVSoBAHrVxHL16zt4H5OvwBmdfgs4F3auPE0NZBx5PmIujBAdqw0Cv4bZACXytT1O1y6FHEZA25E1aqQZD"
},
{
"id": "3326848fdgsdfgsdf03424168",
"name": "name2",
"access_token": "CAAIf3VEtVSoBAJinePVdfgsdfgMxuY3zaj9AimaoKx7VIO9jCqZCHC6ZBixL1n6ZC72LTMn0ZB4T8rOHD27WmzbBVgvUwgspeEZD"
}
]
}
And php:
$val = json_decode($read, TRUE);
echo $val['data'][0]['id'];
UPDATED:
function find_by_id($id, $val) {
foreach($val['data'] as $key => $obj) {
if ($obj['id'] === $id)
return $obj['access_token'];
}
}