Getting multiple keys' values from JSON with PHP - php

I am trying to extract team names, players name from this json. but get no resul.
My json file looks like. any idea where I am wrong ?
{"items":[
{"_id":305501,"id":"305501","created_at":"2015-10-19T19:57:02+13:00","updated_at":"2015-10-19T21:34:50+13:00","name":"Match in progress","verification_level":0,
"club_one":{"name":"Degree Club","id":14748,
"team":{"name":"Degree College XI","id":13009,"avatar":"/original/team/default_thumb.png",
"players":[
{"id":null,"name":"D Vinaya"},
{"id":617744,"name":"V Avika"},
{"id":617745,"name":"C Rumes"},
{"id":1360372,"name":"R Ferdo"}
],
"innings":[{"overs":34,"over_balls":0,"runs":99,"wickets":7}]
}
},
"club_two":{"name":"George Club","id":147736,
"team":{"name":"George College XI","id":154503,"avatar":"/original/team/default_thumb.png",
"players":[
{"id":null,"name":"M Premathe†"},
{"id":null,"name":"S Tion"},
{"id":null,"name":"N Perra"},
{"id":1400317,"name":"S Ren"}
],
"innings":[]
}
},
"processed":true,"visible":true,"match_level":{"name":null,"id":null}
}
],
"meta":{"total_pages":1}
}
and here is the php code.
$json_file = json_decode($load_json);
foreach ($items as $item) {
echo $item->$json_file->_id;
echo $item->$json_file->club_one;
echo $item->$json_file->club_two;
}

You are doing it wrong. As far as your json is concerned, loop it like this
$json_file = json_decode($json);
foreach ($json_file->items as $item) {
echo $item->id;
echo $item->club_one->name;
echo $item->club_two->name;
}

Related

JSON Get the name of dynamically changing key with PHP

I am having trouble getting the name of a dynamic key from a JSON string.
I am using PHP
This is a sample of the JSON
{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}
I am using foreach to go trough the json key and get the values
foreach ($json as $obj) {
$search_term = $obj->_text;
$msg_id = $obj->msg_id;
}
But I am not sure how to get the value of the "dynamic_key" which changes every time, and because of that I also cannot get the values of "confidence and value" keys.
Any ideas on how to approach this?
Followed #Dimi, solution. This is what I ended up with
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "Entity: $key";
foreach ($data['entities'] as $keys){
$conf = $keys[0]['confidence'];
$answer = $keys[0]['value'];
echo "conf: $conf, answ: $answer";
}
}
Can you provide a couple more examples?
Or try this code and let us know if it breaks
<?php
$json='{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}';
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "VALUE IS $key\n values are ";
var_dump($val);
}
Using the data you've shown, there doesn't seem to be an array for the starting JSON.
But with that data the following will use foreach to both fetch the key and the data and then another sub-loop to fetch the confidencevalue...
$search_term = $json->_text;
$msg_id = $json->msg_id;
foreach ( $json->entities as $key => $entities ) {
echo $key.PHP_EOL;
foreach ( $entities as $entity) {
echo $entity->confidence.PHP_EOL;
}
}
If you decode the JSON as an array and if the dynamic key is the only key under entities, then:
$array = json_decode($json, true);
$dynamic = current($array['entities']);
$confidence = $dynamic['confidence'];
$value = $dynamic['value'];
Or shorter:
$confidence = current($array['entities'])['confidence'];
You can probably use reset, current and maybe array_pop etc.

Issues with decoding json object

Thanks for your time in reading this post.
My php file is receiving a json object. But I am facing issues while decoding it.
My php code:
$data=$_POST['arg1'];
echo $data;
$json = json_decode($data,true);
echo $json;
$i = 1;
foreach($json as $key => $value) {
print "<h3>Name".$i." : " . $value . "</h3>";
$i++;
}
When I echo data results as below.
{
"SCI-2": {
"quantity": 2,
"id": "SCI-2",
"price": 280,
"cid": "ARTCOTSB"
}
}
When I echo $json, result is as it follows :
Array
Name1 : Array.
Please assist as i need tho access the cid and quantity values in the $data.
json_decode returns an array. And to print array you can use print_r or var_dump.
Now to access your values you can try :
$json["SCI-2"]["quantity"] for quantity and $json["SCI-2"]["cid"] for cid.
Demo : https://eval.in/522350
To access in foreach you need this :
foreach($json as $k) {
foreach($k as $key => $value) {
print "<h3>Name".$i." : " . $value . "</h3>";
}
}
Since you do not know the number of items in your object, use this:
$obj = json_decode($json);
After this, iterate the $obj variable and after that, inside the loop, use the foreach to get each property.
foreach($iteratedObject as $key => $value) {
//your stuff
}

As I read this Json in php?

I am starting my knowledge of php , I have difficulty reading this array in json , I can read all the information , but I can not read data off geofences array
How can read the information contained within " geoFences " id and name ?
My json example
I need read this in php json.
$response =
[
{
"id":441818,
"device":{
"id":6,
"uniqueId":"35390906000",
"name":"440",
"description":"COOR",
"timeout":3000,
"idleSpeedThreshold":0.0,
"iconType":{
"OFFLINE":{
"width":21,
"height":25,
"urls":[
"/img/marker-white.png",
"http://cdnjs.cloudflare.com/ajax/libs/openlayers/2.13.1/img/marker-green.png"
]
},
"LATEST":{
"width":21,
"height":25,
"urls":[
"http://cdnjs.cloudflare.com/ajax/libs/openlayers/2.13.1/img/marker.png",
"http://cdnjs.cloudflare.com/ajax/libs/openlayers/2.13.1/img/marker-green.png"
]
}
}
},
"time":"Fri, 07 Aug 2015 23:13:06 -0300",
"valid":true,
"latitude":-23.1,
"longitude":-46.1,
"altitude":745.0,
"speed":0.0,
"course":0.0,
"other":"\u003cinfo\u003e\u003cbattery\u003e58\u003c/battery\u003e\u003cip\u003e179.95.37.54\u003c/ip\u003e\u003c/info\u003e",
"geoFences":[
{
"id":16,
"name":"PL Eldorado",
"color":"20B2AA"
}
]
}
]
I need read in php this information...
"id":16,
"name":"PL Eldorado".
Example, if i need read device->name i do it:
$json=json_decode($response, true);
foreach ($json as $person_name => $person)
{
echo $person['device']['name'];
}
But i do it, don´t work.
$json=json_decode($response, true);
foreach ($json as $person_name => $person)
{
echo $person['geoFences']['id'];
echo $person['geoFences']['name'];
}
You have another array under geoFences.
This is the loop:
foreach($json as $person){
foreach($person['geoFences'] as $g){
echo $g['id'].'<br>';
echo $g['name'].'<br>';
}
}

PHP echo JSON nested array values

I want to echo all expanded_url and urls. echo $name prints results . echo $value doesn't print anything because of nested array. How do I echo all values?
$json ='{ "results" : [ { "entities" :
[ { "urls" : [ { "expanded_url" : "http://www.google.com",
"url" : "http://t.co/WZnUf68j"
}, { "expanded_url" : "http://www.facebook.com",
"url" : "http://t.co/WZnUf68j"
}, { "expanded_url" : "http://www.twitter.com",
"url" : "http://t.co/WZnUf68j"
} ] } ],
"from_user" : "A-user-name",
"from_user_id" : 457304735,
"text" : "Ich R U #BoysNoize #SuperRola"
} ] }';
# $json_array = (array)(json_decode($json));
$data = json_decode($json,true);
foreach($data as $name => $value){
echo $name.'<br>';
echo $value; // NOT WORKING - HOW TO ECHO ALL VALUES
}
You can do that with
$data = json_decode($json,true);
foreach($data["results"][0]["entities"][0]["urls"] as $value){
echo $value['expanded_url']."\n";
echo $value['url']."\n";
}
Since it's a multidimensional array, you can loop through the various levels to reach where you want.
foreach($data['results'] as $item) {
foreach($item['entities'] as $urls) {
foreach($urls['urls'] as $element) {
echo "expanded_url: {$element['expanded_url']} \n";
echo "url: {$element['url']} \n";
}
}
}
Note: The reason I've done the various foreach loops is due to the fact that there may be different results or different entities, so it's better to loop, than to do foreach($data["results"][0]["entities"][0]["urls"] as $value)
Example

PHP - How to Loop through JSON array with fields starting with "$"

I have been trying to workout how to loop through and output the contents of a json file where field names start with "$" and keep getting an Undefined variable error message
Here is an example of the json file example (taken from https://mixpanel.com/help/reference/webhooks):
[
{
"$distinct_id":"13b20239a29335",
"$properties":{
"$region":"California",
"$email":"harry.q.bovik#andrew.cmu.edu",
"$last_name":"Bovik",
"$created":"2012-11-20T15:26:16",
"$country_code":"US",
"$first_name":"Harry",
"Referring Domain":"news.ycombinator.com",
"$city":"Los Angeles",
"Last Seen":"2012-11-20T15:26:17",
"Referring URL":"http://news.ycombinator.com/",
"$last_seen":"2012-11-20T15:26:19",
}
},
{
"$distinct_id":"13a00df8730412",
"$properties":{
"$region":"California",
"$email":"anna.lytics#mixpanel.com",
"$last_name":"Lytics",
"$created":"2012-11-20T15:25:38",
"$country_code":"US",
"$first_name":"Anna",
"Referring Domain":"www.quora.com",
"$city":"Mountain View",
"Last Seen":"2012-11-20T15:25:39",
"Referring URL":"http://www.quora.com/What-...",
"$last_seen":"2012-11-20T15:25:42",
}
}
]
I am testing with a static string just to try and get things working. Here is my test code...
<?php
$input = '[{"$distinct_id":"13b20239a29335","$properties":"dddd"}]';
$jsonObj = json_decode($input, true);
foreach ($jsonObj as $item) {
foreach ($item as $rec) {
echo '<br>';
$my_id = $rec->$distinct_id;
echo($my_id);
$my_id = $rec->$properties;
echo($my_id);
}
echo '<br>';
}
?>
Any help would be appreciated.
Noob!
UPDATE: Musa gave this example which works for the single level json:
foreach ($jsonObj as $item) {
echo '<br>';
$my_id = $item->{'$distinct_id'};
echo($my_id);
$my_id = $item->{'$properties'};
echo($my_id);
echo '<br>';
}
How can this then be adapted to read and output all elements of the bigger multi-level json file?
Use Curly bracket notation
$object->{'$property'};
Edit
foreach ($jsonObj as $item) {
echo '<br>';
$my_id = $item->{'$distinct_id'};
echo($my_id);
foreach ($item->{'$properties'} as $my_prop => $value){
echo("$my_prop => $value");
}
echo '<br>';
}
http://codepad.org/1cudZqlu
With the nested loop you're iterating the properties $distinct_id and $properties so $rec is actually a string and not an object.
Also your json is invalid as it has trailing , in the $properties field.

Categories