How to get json property name with php - php

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 !

Related

How to access associate array of array in php?

I'm from Perl but I'm beginner in PHP. I'm having following array
$rating_data = Array ("51" => Array (5,3,4,2));
I'm trying to access the each data using loop so I tried following
foreach ($keys as $rating_data)
{
foreach ($index as $rating_data[$keys])
{
echo "$index";
}
}
But the above one is not working. I have also tried the below one also,
$all_keys = array_keys($rating_data);
foreach ($keys as $all_keys)
{
foreach ($values as $all_keys)
{
echo "$values";
}
}
But I didn't get the output. It works if I hard code the keys like below:
$rating_data["51"][0];
How to fix this issue.?
You can get the key position and iter value ( sencod level ).
foreach($rating_data as $key => $values)
{
echo $key; // Output "51"
foreach($values as $value)
{
echo $value; // Output: iter1: "5", iter2: "3", iter3: "4", iter1: "2",
}
}
It should be as simple as below:
foreach($rating_data as $key => $values) {
echo $key;
foreach($values as $value) {
echo $value;
}
}
You seem to have your parameters the wrong way around in your foreach statements. I would advise a quick read through the foreach docs.

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
}

PHP - Getting array element from Json

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 />";
}
}
}

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.

Retrieving array keys from JSON input

I have this array:
$json = json_decode('
{"entries":[
{"id": "29","name":"John", "age":"36"},
{"id": "30","name":"Jack", "age":"23"}
]}
');
and I am looking for a PHP "for each" loop that would retrieve the key names under entries, i.e.:
id
name
age
How can I do this?
Try it
foreach($json->entries as $row) {
foreach($row as $key => $val) {
echo $key . ': ' . $val;
echo '<br>';
}
}
In the $key you shall get the key names and in the val you shal get the values
You could do something like this:
foreach($json->entries as $record){
echo $record->id;
echo $record->name;
echo $record->age;
}
If you pass true as the value for the second parameter in the json_decode function, you'll be able to use the decoded value as an array.
I was not satisfied with other answers so I add my own. I believe the most general approach is:
$array = get_object_vars($json->entries[0]);
foreach($array as $key => $value) {
echo $key . "<br>";
}
where I used entries[0] because you assume that all the elements of the entries array have the same keys.
Have a look at the official documentation for key: http://php.net/manual/en/function.key.php
You could try getting the properties of the object using get_object_vars:
$keys = array();
foreach($json->entries as $entry)
$keys += array_keys(get_object_vars($entry));
print_r($keys);
foreach($json->entries[0] AS $key => $name) {
echo $key;
}
$column_name =[];
foreach($data as $i){
foreach($i as $key => $i){
array_push($column_name, $key);
}
break;
}
Alternative answer using arrays rather than objects - passing true to json_decode will return an array.
$json = '{"entries":[{"id": "29","name":"John", "age":"36"},{"id": "30","name":"Jack", "age":"23"}]}';
$data = json_decode($json, true);
$entries = $data['entries'];
foreach ($entries as $entry) {
$id = $entry['id'];
$name = $entry['name'];
$age = $entry['age'];
printf('%s (ID %d) is %d years old'.PHP_EOL, $name, $id, $age);
}
Tested at https://www.tehplayground.com/17zKeQcNUbFwuRjC

Categories