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.
Related
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 is the JSON
{
"circuit_list": [
{
"_id": "58c0f378a986f808cdaf94cf",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
},
{
"_id": "58c0f378a986f808cdaf94d0",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
}
}
I already try with this code
$json = json_decode($url, true);
foreach($json as $value)
{
$_id = $value->_id;
}
it didn't work. Please help, I need to get the value to show them on the view. Did I do this wrong? this json is difficult because i didn't understand the structure.
I usually decode json with format
[{"id":"1","name":"faisal"}]
like this and with my foreach it's working.
If the second parameter of json_decode is true, the function will return an array instead of an object. Also, you would need to loop over the circuit_list property of the object.
$json = json_decode($url); // <- remove the parameter
foreach($json->circuit_list as $value) // <- loop over circuit_list
{
$_id = $value->_id;
}
<?php
$json = json_decode($url,true);
foreach($json['circuit_list'] as $value)
{
$id = $value['_id'];
}
?>
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);
}
I am accessing an API where the JSON data is returned as below.
{
"name": "",
"count": 4,
"frequency": "",
"version": 3,
"newdata": true,
"lastrunstatus": "success",
"thisversionstatus": "success",
"thisversionrun": "",
"results": {
"collection": [{
"textlink": {
"href": "http://text1.com",
"text": "Text 1"
},
"index": 1,
"url": ""
}, {
"textlink": {
"href": "http://text2.com",
"text": "Text 2"
},
"index": 2,
"url": ""
}, {
"textlink": {
"href": "http://text3.com",
"text": "Text 3"
},
"index": 3,
"url": ""
}, {
"textlink": {
"href": "http://text4.com",
"text": "Text 4"
},
"index": 4,
"url": ""
}]
}}
As you can see the JSON tree returned has multi-step levels. I am wanting to be able to take some of the deeper levels, in PHP, and insert into a database.
Currently I am using this code to try and echo the data (once I am able to I can then work on inserting it to a database no problem)
<?php
$request = "API.REQUEST.NET";
$response = file_get_contents($request);
$results = json_decode($response, TRUE);
foreach($results as $item) {
echo $item->results[0]->collection[0]->textlink[0]->href;
echo "<br>";
echo $item->results->collection['href'];
echo "<br>";
echo $item->results->collection['text'];
}
?>
As you can see above I have tried several ways to access the deeper levels f data that are being displayed but with no avail.
I am currently getting errors of 'trying to get property of a non-object'. How is it possible to reach the data in this array?
try:
echo $results['results']['collection'][0]['textlink']['href'];
$obj = json_decode( $json, true ); foreach ( $obj['key'] as $key => $value ) { echo $value; }
foreach ($response['results']['collection'] as $textlink) {
$row = $textlink['textlink'];
echo $row['href'];
echo "<br>";
echo $row['text'];
echo "<br>";
}
you can do foreach like this, which loops only items in collection
I would suggest to do something like this (According to me, correct way to fetch results from API responses):
<?php
$request = "API.REQUEST.NET";
$response = file_get_contents($request);
$response = json_decode($response);
foreach($response->results->collection as $item) {
echo $item->textlink->href;
echo "<br>";
echo $item->textlink->text;
echo "<br>";
echo $item->index;
echo "<br>";
echo $item->url;
}
?>
I have the following JSON object returned from an API call in the $result variable, and my problem is that I need to access the "name" item in each list, but it doesn't work
{
"status": "success",
"data": {
"lists": [
{
"id": "0032",
"name": "Stan",
"status": "active",
},
{
"id": "0043",
"name": "David",
"status": "active",
},
{
"id": "2323",
"name": "Robert",
"status": "pending",
}
]
}
}
Code :
if (isset($result)) {
$json_object = json_decode($result, true);
echo $json_object['status'];
echo $result;
if ($json_object['status'] == 'success') {
$json_object2 = $json_object['data'];
foreach ($json_object['data'] as $key => $value){
foreach ($value as $key2 => $value2){
echo $key2 . " : " . $value2 . "</br>";
}
}
} else {
echo $json_object['data'];
}
}
Try something like this
<?php
$result = '{"status":"success","data":{"lists":[{"id":"0032","name":"Stan","status":"active"},{"id":"0043","name":"David","status":"active"},{"id":"2323","name":"Robert","status":"pending"}]}}';
$json_object = json_decode($result, true);
foreach($json_object['data']['lists'] as $item)
{
echo $item['name']."<br>";
}
?>