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.
Related
So I would like to create just one loop to parse the json data i have. I can successfully parse it in 2 foreach loops however when trying to combine in one loop using $key => $value the $key returns nothing when called. How can I successfully take the 2 foreach loops I have here and combine them into one?
$contents = file_get_contents($url);
$results = json_decode($contents, true);
$jsonList = $results['genres'];
foreach($jsonList as $key) {
$GenreID = $key['id'].'<br>';
echo $GenreID;
}
foreach($jsonList as $key => $value) {
$GenreName = $value['name'].'<br><br>';
echo $GenreName;
}
The json data is as follows:
{"genres":[{"id":28,"name":"Action"},{"id":12,"name":"Adventure"},{"id":16,"name":"Animation"},{"id":35,"name":"Comedy"},{"id":80,"name":"Crime"},{"id":99,"name":"Documentary"},{"id":18,"name":"Drama"},{"id":10751,"name":"Family"},{"id":14,"name":"Fantasy"},{"id":36,"name":"History"},{"id":27,"name":"Horror"},{"id":10402,"name":"Music"},{"id":9648,"name":"Mystery"},{"id":10749,"name":"Romance"},{"id":878,"name":"Science Fiction"},{"id":10770,"name":"TV Movie"},{"id":53,"name":"Thriller"},{"id":10752,"name":"War"},{"id":37,"name":"Western"}]}
You can still use $key as an index when also extracting the $value.
However note that you shouldn't be assigning the line breaks to your variables, and should instead consider them part of the view by echoing them out independently:
$contents = file_get_contents($url);
$results = json_decode($contents, true);
$jsonList = $results['genres'];
foreach($jsonList as $key => $value) {
$GenreID = $key['id']; // Depending on structure, you may need $value['id'];
$GenreName = $value['name'];
echo $GenreID . '<br>';
echo $GenreName . '<br><br>';
}
Your single loop below here.
foreach($jsonList as $key)
{
$GenreID = $key['id'].'<br>';
echo $GenreID;
$GenreName = $value['name'].'<br><br>';
echo $GenreName;
}
$key is a assosative array.Therefore it had some index.So you can use this index in single loop.
It seems you get confused over your data structure. Seeing the json, the resulting "$jsonlist" supposed to contain array with id and value as keys.
You can iterate over it and extract the the appropriate key.
Myabe something like this:
foreach($jsonlist as $value) {
echo "id: " . $value['id'] . "\n";
echo "name: " . $value['name'] . "\n";
}
extra bonus, if you want to create 1 level array from your json based on id with the name you could try array reduce using anon function like this:
$jsonlist = array_reduce($jsonlist, function($result, $item){
$result[$item['id']] = $item['name'];
return $result;
}, []);
extra neat for transformation of static structure data.
So here's the thing, I get this json from a url ( in my context i get it from a url, but let's say here I write my json in a variable :
$file = '[
{"status": "5.4.1","email": "dddddd#exelcia-it.com"},
{"status": "5.4.1",, "email": "sksksksk#exelcia-it.com"}
]'
Then I do $json = json_decode($file,true);
And I want to get all the emails so I do :
foreach ($json as $key => $value) {
echo $value["email"]. "<br>";
}
But what I also need, is to return something like that from the loop (only for one property):
"email = dddddd#exelcia-it.com".
So I need to also get the name of the property but I can't figure this out.
I tried
foreach($json as $key => $propName){
echo $key.'<br>';
}
But I just get the index (0,1,...), not what I want.
Thanks!
You have to loop each json row, this should works:
$file = '[{"status": "5.4.1","email": "dddddd#exelcia-it.com"},{"status": "5.4.1", "email": "sksksksk#exelcia-it.com"}]';
$json = json_decode($file,true);
foreach($json as $row)
{
foreach($row as $key => $value)
{
echo "<b>".$key."</b>".':'.$value.'<br>';
}
}
Use this loop to get key and value pairs together.
foreach($data as $row)
{
foreach($row as $key => $val)
{
echo $key . ': ' . $val;
echo '<br>';
}
}
Ok thanks that's what I needed !
For me I just need the email properties and values, so I do :
foreach($json as $row)
{
foreach($row as $key => $value)
{
if($key=='email'){
echo "<b>".$key."</b>".':'.$value.'<br>';
}
}
}
Awesome ! thanks !
I want to find index of key from json array similar to this question Get index of a key in json
but i need the solution using php.
here is my json (partial data)
{
"currentOver":{
"events":[]
},
"matchString":"",
"currentPlayer":5,
"previousOvers":[],
"innings":[],
"scorecards":[
{
"batting":{
"players":[
{"id":16447,"name":"Rahul Roy"},
{"id":12633,"name":"Sijal Thomas"},
{"id":16446,"name":"Mohammed Reza"},
{"id":16509,"name":"Asif Khan"},
{"id":12633,"name":"Koyel Dijesh"},
{"id":16468,"name":"Shahrook"},
{"id":64691,"name":"Shafiq"},
{"id":6518,"name":"Ubaidulah"}
]
}
}
]
}
and php
foreach ($read_json->scorecards->batting->players as $batsmen => $val) {
if($val == 5) { // if batsman index is 5 then display his name
$name = $batsmen->name;
echo "<div>$name</div>\n";
}
}
Please help me to solve this issue.Thanks in advance.
I think this would suffice your requirement
http://codepad.org/XQDCKAsB
Find the code sample below as well.
$json = '{"currentOver":{"events": []},"matchString":"","currentPlayer":5,"previousOvers":[],"innings":[],"scorecards":[{"batting":{"players":[{"id":16447,"name":"Rahul Roy"},{"id":12633,"name":"Sijal Thomas"},{"id":16446,"name":"Mohammed Reza"},{"id":16509,"name":"Asif Khan"},{"id":12633,"name":"Koyel Dijesh"},{"id":16468,"name":"Shahrook"},{"id":64691,"name":"Shafiq"},{"id":6518,"name":"Ubaidulah"}]}}]}';
$arr = json_decode($json);
echo '<pre>';
$currentPlayer = $arr->currentPlayer;
echo $arr->scorecards[0]->batting->players[$currentPlayer-1]->name;
Try this code.
$info = json_decode('json string');
$currentPlayer = $info->currentPlayer;
$batsman = $info->scorecards[0]->batting->players[$currentPlayer];
echo "<div>{$batsman->name}</div>\n";
Also, note that arrays in PHP are zero-based. If currentPlayer index in json data is based on 1 (rare case, but it exists sometimes) you will ned to use
$batsman = $info->scorecards[0]->batting->players[$currentPlayer - 1];
to get right item from array.
If you just want to fix your foreach
$read_json->scorecards->batting should become $read_json->scorecards[0]->batting
if($val == 5) should become if($batsmen == 5)
$name = $batsmen->name; should become $name = $val->name;
You need to use json_decode and array_keys for the array keys from the json.
$json = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
$result = json_decode ($json, true);
$keys = array_keys($result);
print_r($keys); //Array ( [0] => key1 [1] => key2 [2] => key3 )
In Php, You can use the code below, if you wan to fix it using foreach loop
foreach($json->entries as $row)
{
foreach($row as $key => $val)
{
echo $key . ': ' . $val;
echo '<br>';
}
}
please have a look following code
$json=json_decode($data)->scorecards[0]->batting->players;
foreach ($json as $key => $value) {
if($key==5){
echo $value->name ;
}
}
You can do it using converting JSON string to Array
$json_str = '{
"currentOver":{
"events":[]
},
"matchString":"",
"currentPlayer":5,
"previousOvers":[],
"innings":[],
"scorecards":[
{
"batting":{
"players":[
{"id":16447,"name":"Rahul Roy"},
{"id":12633,"name":"Sijal Thomas"},
{"id":16446,"name":"Mohammed Reza"},
{"id":16509,"name":"Asif Khan"},
{"id":12633,"name":"Koyel Dijesh"},
{"id":16468,"name":"Shahrook"},
{"id":64691,"name":"Shafiq"},
{"id":6518,"name":"Ubaidulah"}
]
}
}
]
}';
Decode your JSON string using "json_decode" and you get array
$json_decode_str = json_decode($json_str, true);
Now using foreach you can do anything
if($json_decode_str['scorecards']){
foreach($json_decode_str['scorecards'] as $scorecard){
$player_index = 1;
if($scorecard['batting']['players']){
foreach($scorecard['batting']['players'] as $player){
if($player_index == 5){
echo $player['name'];
}
$player_index++;
}
}
}
}
Maybe this one help you :)
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
}
I'm working with the JSON here: http://steamcommunity.com/id/mitch8910/inventory/json/730/2/
I'm trying to get the tags[{"name":""}] part of it. For example, I would want the 'container', from '"name":"Container"'
This is my code here:
$data = file_get_contents('http://steamcommunity.com/id/mitch8910/inventory/json/730/2/');
$json = json_decode($data);
foreach ($json->rgDescriptions as $mydata)
{
echo $mydata->tags[1];
}
tags[] is an array, though I did tags[1], I don't awlays want the '1'th element because the position of "name" could change in the array for different elements, I just did this to test, but I got an error. I have tried multiple ways with multiple errors, that why I'm not posting all the error code.
The simplest way may be to do an extra loop to grab all the name elements:
$data = file_get_contents('http://steamcommunity.com/id/mitch8910/inventory/json/730/2/');
$json = json_decode($data);
foreach ($json->rgDescriptions as $mydata)
{
foreach($mydata->tags as $tag) {
echo $tag->name;
}
}
or to get the first name of each tag group:
foreach ($json->rgDescriptions as $mydata)
{
echo $mydata->tags[0]->name;
}
I updated the whole answer:
$json = json_decode($data, true);
if (isset($json['rgDescriptions']) && is_array($json['rgDescriptions'])){
foreach ($json['rgDescriptions'] as $array_no => $value) {
if (isset($json['rgDescriptions'][$array_no]['tags'])){
echo "{$array_no}::::";
foreach ($json['rgDescriptions'][$array_no]['tags'] as $k => $value) {
if (isset($json['rgDescriptions'][$array_no]['tags'][$k]['name'])){
echo "{$json['rgDescriptions'][$array_no]['tags'][$k]['name']},";
}
}
echo "<br />";
}
}
}