I'm trying to parse a full JSON structure. I've been able to get individual nested objects, but I was hoping it could be much simple than looking for each nested structure.
Here's the JSON structure I have:
{
"request1": {
"nest11": "solution11",
"nest12": "solution12"
},
"request2": {
"nest21": "solution21",
"nest22": "solution22"
},
"request3": true,
"request3": {
"nest31": "solution31",
"nest32": "solution31",
"nestnest1": {
"nestnest11": "nestsolution11",
"nestnest12": "nestsolution12"
},
"nestrequest2": {
"nestrequest21": [{
"nestnest21": "solution21",
"nestnest22": "solution22"
}]
},
"request4": "solution4"
}
}
When I get the response from an API, let's say $serverResponse, I'm decoding to get object
$newobj = json_decode($serverResponse);
foreach ($newobj->request1 as $key=>$value) {
$request1 = "request1.".$key.": <b>". $value."</b><br/>";
}
I then send it back to the front end to print it. Question is how do I do it so I don't have to go through each objects and get individual values. I need to print all the key values whether nested or not. Thanks for any pointers and help!
function recursivePrinter($data){
foreach($data as $k=>$v){
if(is_array($v)) recursivePrinter($v);
else echo "$k - $v";
}
}
recursivePrinter(json_decode($response, true));
function recursivePrinter($data, $nested=""){
foreach($data as $k=>$v){
if(is_array($v)){ recursivePrinter($v, $k); }
else echo "$nested.$k - $v";
}
}
recursivePrinter(json_decode($response, true));
Related
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.
Im studying in array, and I was wondering How can I add key to this kind of array?
{
"items":[
{
"count":"1",
"id":123,
"description":"Bag",
"price":11
},
{
"count":1,
"id":1234,
"description":"10% Discount",
"price":-1.1
}
],
"total":9.9,
"discount_total":9.9
}
because I needed convert the array to have a key base on the id inside the array.
{
"items":{
"123":{
"count":"1",
"cart_id":123,
"description":"Bag",
"price":11
},
"1234":{
"count":1,
"cart_id":1234,
"description":"10% Discount",
"price":-1.1
}
},
"total":9.9,
"discount_total":9.9
}
and this is my code
header('Content-Type: application/json');
$cart_array = json_decode('{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Bag"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}');
foreach ($cart_array->items as $item)
{
$construct["cart_id"] = $item->cart_id;
}
I wanted to ask how can I put the id in the array? I cant use $cart_array['id'] = $value, it returns error.
Uncaught Error: Cannot use object of type stdClass as array
I could really use some explanation here
Following code can help you.
<?php
$json = '{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Small Four Seasons"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}';
$data = json_decode($json,TRUE); //json decode
foreach ($data['items'] as $key => $value)
{
$data['items'][$value['cart_id']] = $value;
unset($data['items'][$key]);
}
echo "<pre>";print_r($data);die;
?>
You don't have to loop at all. You can use array_column to make an array associative with one line of code.
$cart_array['items'] = array_column($cart_array['items'], NULL, 'cart_id');
https://3v4l.org/cPD5n
You can use this code in your application to add keys to indexed array.
foreach($obj as $key=>$val){
foreach ($val as $index=>$content){
$data[$content['id']]=$content;
}
}
You can get same output json data as per you want :
$array = json_decode($data,true);
if(isset($array['items']) && count($array['items']) > 0){
foreach($array['items'] as $key => $value){
$value['cart_id'] = $value['id'];
unset($value['id']);
$array['items'][$value['cart_id']] = $value;
unset($array['items'][$key]);
}
}
echo "<pre>";print_r($array);
echo json_encode($array);
I have some JSON I need to parse in a file test.json.
{
"players":
[
{ "SteamId":123, "Username":"Bob", "Kills":5, "Deaths":7, "Rank":1 },
{ "SteamId":456, "Username":"Nick", "Kills":3, "Deaths":2, "Rank":2 },
{ "SteamId":789, "Username":"Moses" "Kills":8, "Deaths":1, "Rank":3 }
]
}
How can I loop through and display my data. My code so far when I var_dump gives me a NULL
$raw_data = file_get_contents('test.json');
$data = json_decode($raw_data, true);
var_dump($data);
Your code is fine once you place the comma Saty mentioned.
To loop and print some values it would look something like:
foreach($data["players"] as $player){
print "Steam ID: ".$player['SteamId'];
print "Username: ".$player['Username'];
print "Kills: ".$player['Kills'];
print "Deaths: ".$player['Deaths'];
print "Rank: ".$player['Rank'];
}
This could be improved to automatically use the Key value as output with the following:
foreach($data["players"] as $player){
foreach($player as $key => $value){
print $key.": ".$value;
}
}
Depends what you are trying to accomplish and how the data will be viewed, but I expect you would be using HTML template.
I have a json file which I decode using json_decode. The json file is an object which holds two arrays. I only want the first array but I'm having trouble figuring out how.
Json file
{
"app":{
"available":{
"stats":[
{
"name":"the name",
"at":"url"
},
{
"name":"the name",
"at":"url"
}
],
"stats2":[
{
"name":"the name",
"at":"url"
},
{
"name":"the name",
"at":"url"
}
]
}
}
}
I use
foreach($data3['app']['available'] as $name => $value)
{
foreach($value as $entry)
{
echo $entry['name'];
}
}
The output I get every name from both stats1 and stats2 arrays. I only want the names from stats1 array, not stats2. How can this be achieved?
because there are two arrays in app->available: stats and stats2
If you are interested in only stats, why don't you try:
foreach($data3['app']['available']['stats'] as $name => $value)
__UPDATE__
Try this one please
$in = '{"app":{"available":{"stats": [{"name":"the name","at":"url"},{"name":"the name", "at":"url"}],"stats2":[{"name":"the name","at":"url"},{"name":"the name","at":"url"}]}}}';
$obj = (array) json_decode($in, true);
foreach($obj['app']['available']['stats'] as $value)
{
foreach($value as $e => $v)
{
echo ($value['name'] );
echo ("\r");
}
}
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.