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
Related
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.
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;
}
?>
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'm using PHP and json_decode to use a remote API and I'm having what seems to be a newbie problem for which I didn't even know what to search to find my answer.
So on my script I have a $code = 392 and a json file which simplified version is:
{
"result": {
"items": [
{
"name": "New York",
"code": 7294,
},
{
"name": "Miami",
"code": 392,
},
{
"name": "Los Angeles",
"code": 9182,
}
]
}
}
So, simply put, having the code 392 I want to know which name corresponds to that code. How ?
(The actual json result has thousands of "items", if that makes a difference)
At first you should decode your json data like:
// will decode json data as assoc array
$data = json_decode($json_data, true);
Then, you can get value in this array like:
$item01 = $data['result']['items'][0];
$name = $item01['name']; // New York
$code = $item01['code']; // 7294
Or
// will decode json data as object
$data = json_decode($json_data);
$item01 = $data->result->items[0];
$name = $item01->name; // New York
$code = $item01->code; // 7294
You can iterate through items in result of your JSON object, and check for equality with the desired code, and each item's code. Here's how you would implement it into a function.
function getNameFromCode($json, $code) {
foreach ($json['result']['items'] as $item)
if ($item['code'] == $code)
return $item['name'];
// return false if the code wasn't found.
return false;
}
// assume this is the JSON string of your example.
$json_string = "...";
// pass true as the second argument to get an associative array.
$json = json_decode($json_string, true);
// should return "Los Angeles".
$name = getNameFromCode($json, 9182);
Documenation on foreach().
foreach( json_decode($my_json_string) as $key => $item)
if ( $item['code'] === $code ) { $name = $item[name]; break; }
You can convert JSON to PHP object and loop through the items with foreach loop.
function getNameByCode($phpobj, $code){
if( isset($phpobj->result) ){
if( isset($phpobj->result->items)
&& is_array($phpobj->result->items) ){
foreach($phpobj->result->items as $item){
if( $item->code == $code ){
return $item->name;
}
}
}
}
return false;
}//end function
You can test with this ... NOTE: trailing commas are removed as suggest by rjdown in comment
$json = '{
"result": {
"items": [
{
"name": "New York",
"code": 7294
},
{
"name": "Miami",
"code": 392
},
{
"name": "Los Angeles",
"code": 9182
}
]
}
}';
$phpobj = json_decode($json);
$name = getNameByCode($phpobj, "7294");
echo $name;