How to parse through multiple layers of JSON - php

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.

Related

Print strings in PHP where item orders are collected from JSON

I have a JSON item list in the database that holds the the serial number of different items to be printed according to the order of their serial number. The JSON structure is like this:
{
"item_list": [
{
"item_sl": "1",
"item_print": "flowers"
},
{
"item_sl": "2",
"item_print": "cars"
}
]
}
After retrieving it from the database, I decoded the items in $items_array and then tried to create variables like $item1, $item2 ... which I wanted to assign to the item_print values from the JSON. The same print values have been already defined earlier ($cars, $flowers). Lastly, I wanted to print all of them. The code is:
$cars = 'Tesla is my favorite.';
$flowers = 'I love all flowers.';
$items_array = json_decode($items_data, true);
foreach ($items_array['item_list'] as $item_list) {
foreach ($item_list['item_sl'] as $key => $n) {
${'item'.$n} = $item_list['item_print'][$key];
}
}
$all_print = $item1.' '.$item2;
echo $all_print;
But $all_print is returning null, which tells me my approach is not correct. What am I missing here? What would be a better approach for printing the $cars and $flowers variables according to the serial numbers from the JSON?
First of all, there is no need to use multiple loops when you can achieve the same with a single loop.
Also, there is no need to create variables dynamically and assign values when you can directly decode the JSON and access each value without creating variables and assigning them dynamically.
This should work:
<?php
$items_data = '{
"item_list": [
{
"item_sl": "1",
"item_print": "flowers"
},
{
"item_sl": "2",
"item_print": "cars"
}
]
}';
$items_array = json_decode($items_data, true);
foreach ($items_array['item_list'] as $item) {
${'item' . $item['item_sl']} = $item['item_print'];
}
$all_print = $item1.' '.$item2;
echo $all_print;
?>
Output:
flowers cars
For Your Code above, i don't Really Understand it well, but i think this may help if you are trying to loop items from a json encoded data.
$items_array = json_decode($items_data, true);
foreach ($items_array->item_list as $item_list) {
echo $item_list->item_sl;
echo $item_list->item_print;
}
EDITED
Two Methods to achieve this
First:
$items_array = json_decode($items_data, true);
foreach ($items_array["item_list"] as $item_list) {
echo $item_list["item_sl"];
echo $item_list["item_print"].'<br>';
}
Second:
$items_array = json_decode($items_data);
foreach ($items_array->item_list as $item_list) {
echo $item_list->item_sl;
echo $item_list->item_print;
}
ADDITIONALLY:
if you want to display output based on the user item_print, then you can do this;
$items_array = json_decode($items_data, true);
foreach ($items_array["item_list"] as $item_list) {
if ($item_list["item_print"] == 'cars') {
echo $cars."<br>";
}elseif($item_list["item_print"] == "flowers"){
echo $flowers;
}
}

Display Php (json) output in tabular format

I am new to Wordpress Plugin Developement,Wrote a function that requests a url for data and gets the same in Json Format,The Function Snippet is as follows;
function user_det()
{
$em = '';
$url = ''.$em;
$myhtml = wp_remote_retrieve_body( wp_remote_get($url, array( 'timeout'=>120)));
echo '<pre>' , print_r($myhtml) , '</pre>';
}
The Output:
{
"Status":"Success",
"Bookings":[
{
"Message":"",
"Detail":{
"ServiceType":"",
"HoName":"",
"HAddress1":"",
"ToRooms":"",
"RoDetail":[
{
"RoomTypeDescription":[
" "
],
"NumberOfRooms":"",
"Passengers":[
{
"Salutations":"",
"FirstName":"",
"LastName":""
},
{
"Salutations":"",
"Age":"",
"CotBedOption":""
}
],
"totalAdult":2,
"totalChild":0
}
],
"Phone":"-",
"Rating":"",
"email":""
}
}]}
However ,Is there a way where I could Display the data in a tabular format,tried searching online but could not understand
As you are getting the information in JSON format from your API request, you'll need to iterate each element to format the way you want, example of building a table using this information.
$myhtml = wp_remote_retrieve_body( wp_remote_get($url, array( 'timeout'=>120)));
$dataArray = json_decode($myhtml,1);
echo '<table>';
echo '<thead><tr><th>Service Type</th></tr></thead>';
echo '<tbody>';
// Now we have the json converted into an array, let's iterate it
foreach($dataArray["Bookings"] as $idx=>$bookingData) {
// Iterate all bookings and write on the rows
echo '<tr>';
echo '<td>'.$bookingData['Detail']['ServiceType'].'</td>';
echo '</tr>';
}
echo '</tbody><table>';
I believe this gives you the idea on what you need to perform to get your object and build a table.

Parsing Decoded nested/mixed JSON in PHP

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));

JSON manipulation in PHP?

I need to edit some data in a JSON file, and I'm looking to do so in PHP. My JSON file looks like this:
[
{
"field1":"data1-1",
"field2":"data1-2"
},
{
"field1":"data2-1",
"field2":"data2-2"
}
]
What I've done so far is $data = json_decode(file_get_contents(foo.json)) but I have no idea how to navigate this array. If for example I want to find the data from the first field of the second object, what's the PHP syntax to do so? Also, are there other ways I should know about for parsing JSON data into a PHP friendly format?
This JSON contains 2 arrays with 2 objects each, you can access like this:
$arr = json_decode(file_get_contents(foo.json));
// first array
echo $arr[0]->field1;
echo $arr[0]->field2;
// second array
echo $arr[1]->field1;
echo $arr[1]->field2;
if you convert this to an array and avoid objects you can then access like this:
$arr = json_decode(file_get_contents(foo.json), true);
// first array
echo $arr[0]['field1'];
echo $arr[0]['field2'];
// second array
echo $arr[1]['field1'];
echo $arr[1]['field2'];
$data = json_decode(file_get_contents(foo.json));
foreach($data as $k => &$obj) {
$obj->field1 = 'new-data1-1';
$obj->field2 = 'new-data1-2';
}
Please use this code to navigate through your json format. This code is dynamic and can navigate for any number of objects you have in your result.
<?php
$json ='[
{
"field1":"data1-1",
"field2":"data1-2"
},
{
"field1":"data2-1",
"field2":"data2-2"
}
]';
if($encoded=json_decode($json,true))
{
echo 'encoded';
// loop through the json values
foreach($encoded as $key=>$value)
{
echo'<br>object index: '.$key.'<br>';
foreach($value as $bKey=>$bValue)
{
echo '<br> '.$bValue.' = '.$bValue;
}
}
// get a perticular item
echo '<br>object[0][field1]: '.$encoded[0]['field1'];
}
else
{
echo'error on syntax';
}
?>
Which will have following output
encoded
object index: 0
data1-1 = data1-1
data1-2 = data1-2
object index: 1
data2-1 = data2-1
data2-2 = data2-2
object[0][field1]: data1-1

loop json array and return values in php

I use a library for Synchronize a local WebSQL DB to a server specifically https://github.com/orbitaloop/WebSqlSync. I use PHP: 5.4.7
this is json var $json
{
"info":"",
"data":{
"clientes":[],
"conceptos_gastos":[],
"formaspago":[{
"idFormaPago":7,
"FormaPago":"quwuw",
"Dias":1,
"Cuotas":1,
"last_sync_date":null
}],
"listaprecios":[],
"producto":[],
"repartidores":[],
"tipodocumento":[],
"vehiculos":[],
"zonas":[]
}
}
when I try to get the values
$js=json_decode($json,true);
foreach ($js['formaspago'] as $row ) {
echo $row["Formapago"];
}
I get this error:
Invalid argument supplied for foreach
any help is appreciated
use json_decode
//array
$data = json_decode($json, true);
foreach($data["data"]["formaspago"] as $row) {
echo $row["Formapago"];
}
Thanks #JimL for the hint.
You're not passing a valid array to the foreach loop. However, even if you parse the json you've supplied, a foreach won't work because it's an object not an array.
$json = '{
"info":"",
"data":{
"clientes":[],
"conceptos_gastos":[],
"formaspago":[{
"idFormaPago":7,
"FormaPago":"quwuw",
"Dias":1,
"Cuotas":1,
"last_sync_date":null
}],
"listaprecios":[],
"producto":[],
"repartidores":[],
"tipodocumento":[],
"vehiculos":[],
"zonas":[]
}
}';
$obj = json_decode($json);
print $obj->info will return an empty string.
$obj->data is an object that has various properties some of which are empty arrays. Passing these into the foreach should work. i.e.
foreach($obj->data->clients as client) {
// Do something here
}
Further, $obj->data->formaspago has exactly one element in the array, which is an object. You can access this object with a foreach loop:
foreach($obj->data->formaspago as formaspago) {
print formaspago->idFormaPago; // Will print 7
print formaspago->FormaPago; // Will print "quwuw"
print formaspago->Dias; // Will print 1
print formaspago->Cuotas; // Will print 1
print formaspago->last_sync_date; // Will print nothing
}

Categories