how do json data become dynamic html tables using php? - php

how the json key is used as the table name, and displays data in the table, without the table name being created
{
"status": "sukses",
"title": "OK",
"img": "ok.jpg",
"data": {
"network": {
"technology": "No cellular connectivity",
"2g_bands": " N\/A",
"gprs": "No",
"edge": "No"
}
}
}
I want to make it like this
statuss title img technology 2g_bands gprs edge
sukses ok ok.jpg No cellular connectivity N\/A No No
with php Below, I am confused how to retrieve the json key to retrieve the name of the table I need to be dynamic
<?php
$Libs = new Library();
$result = $Libs->pilihmodel($idbrand,$idmodel);
if ($result->rowCount()>0) {
while ($datas = $result->fetch(PDO::FETCH_OBJ)) {
$datass = $datas->jsondetail;
$hasiljson = json_decode($datass, TRUE);
$binatang = array($hasiljson);
echo "<table>";
foreach ($binatang as $jenis) {
foreach ($jenis as $nama) {
echo "<td>$nama</td>";
}
}
echo "</table>";
}

You're about halfway there. Getting the keys is easy in a PHP foreach loop using $key => $value) syntax. Then you can, in parallel, build the header row and data row using the key and value from each field. Because of the structure of the JSON you also need to make a special case for the "data" object.
(If the structure is unpredictable you could make a recursive function which would traverse the structure and either print a field if it's a plain string, or find its children if it's another array, but that's probably overkill for what you're doing here. If you really need that though, please mention it.)
This will work:
$hasiljson = json_decode($datass, TRUE);
$header = "";
$body = "";
foreach ($hasiljson as $key => $value)
{
if ($key != "data")
{
$header .= "<td>$key</td>";
$body .= "<td>$value</td>";
}
else
{
foreach ($hasiljson["data"]["network"] as $key1 => $value1)
{
$header .= "<td>$key1</td>";
$body .= "<td>$value1</td>";
}
}
}
echo "<table><tr>$header</tr><tr>$body</tr></table>";
Demo: http://sandbox.onlinephpfunctions.com/code/8b61f2933b0ebf8a3ea1091c1e4474882e8c90a1

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

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.

Create JSON response from Parsed XML PHP

I am parsing thorugh a eBay API response. I want to deliver this back to a website cleaner and easier to parse with JavaScript. I successfuly Parsed through the XML... but now turning that into JSON to resend back to the client is giving me some headaches.
NOTE: $resp is the response from eBay. It's their full length XML that is successfully parsed with the code below.
For example... $valueName could be Grade. And then I go into the next foreach loop and get the values for this. These values may be 10, 9.5, 9 etc.
Here is my PHP code.
$arrayName = array();
$arrayValue = array();
foreach($resp->aspectHistogramContainer->aspect as $name) {
$nameAspect = $name['name'];
//$arrayName["aspectName"] = $nameAspect;
foreach($name->valueHistogram as $value) {
$valueAspect = $value['valueName'];
//$arrayValue["aspectValue"] = $valueAspect;
}
//array_push($arrayName, $arrayValue);
}
echo json_encode($arrayName);
So, without me trying to create my own JSON, I am getting that I need. I echos results and it was similar to this...
NAME
----- Value
----- Value
----- Value
NAME
----- Value
NAME
etc etc
For a JSON response... Im looking for something like...
[
{
"name": "NAME",
"value": ["value", "value"]
}, {
"name": "name",
"value": ["value", "value"]
}
]
Any help and guidance would be greatly appreciated.
eBay's response is like this (there are A LOT more <aspect> and <valueHistogram>)
<getHistogramsResponse xmlns="http://www.ebay.com/marketplace/search/v1/services">
<ack>Success</ack>
<version>1.13.0</version>
<timestamp>2018-11-07T15:32:20.380Z</timestamp>
<aspectHistogramContainer>
<domainDisplayName>Baseball Cards</domainDisplayName>
<aspect name="Card Manufacturer">
<valueHistogram valueName="Ace Authentic">
<count>19</count>
</valueHistogram>
<valueHistogram valueName="American Caramel">
<count>2024</count>
</valueHistogram>
<valueHistogram valueName="APBA">
<count>10554</count>
</valueHistogram>
<valueHistogram valueName="Bazooka">
<count>8826</count>
</valueHistogram>
<valueHistogram valueName="Be A Player">
<count>17</count>
</valueHistogram>
<valueHistogram valueName="Bell Brand Dodgers">
<count>334</count>
To encode it (and assuming SimpleXML), then it's just a case of building each internal $aspect data array and then adding the values to it. I use (string) to ensure the data is not stored as a SimpleXMLElement, which can cause side effects...
$arrayName = array();
foreach($resp->aspectHistogramContainer->aspect as $name) {
$aspect = [ "name" => (string)$name['name']];
foreach($name->valueHistogram as $value) {
$aspect["value"][] = (string)$value['valueName'];
}
$arrayName[] = $aspect;
}
echo json_encode($arrayName);
with the sample XML, this gives...
[{"name":"Card Manufacturer","value":["Ace Authentic","American Caramel","APBA","Bazooka","Be A Player","Bell Brand Dodgers"]}]
Create one single array $resultArray and store values in it. By maintaining your current code structure with minimal changes, here is the updated code snippet,
$resultArray = array();
$i = 0; // Maintain Array Index value
foreach($resp->aspectHistogramContainer->aspect as $name) {
$resultArray[$i]["aspectName"] = (string)$name['name'];;
foreach($name->valueHistogram as $value) {
$resultArray[$i]["aspectValue"][] = (string)$value['valueName'];
}
$i++; // Increment array index to store next value
}
echo json_encode($resultArray);
$results = array();
// Parse the XML into a keyed array
foreach($resp->aspectHistogramContainer->aspect as $name) {
$nameAspect = (string) $name['name'];
$values = array();
foreach($name->valueHistogram as $value) {
$values[] = (string) $value['valueName'];
}
$results[$nameAspect] = $values;
}
// This keeps things simple - rewrite to the required JSON format
$outputForJSON = array();
foreach ($results as $name => $values) {
$outputForJSON[] = array(
"name" => $name,
"values" => $values
);
}
echo json_encode($outputForJSON);

Any JSON to CSV Converter

I am trying to build common function for JSON to CSV Converter. currently for different json file i have to make some changes in existing function.
current code:
function JsonToCSV($jfilename, $cfilename) {
if (($json = file_get_contents($jfilename)) == false)
die('Error reading json file...');
$data = json_decode($json, true);
$fp = fopen($cfilename, 'w');
$header = false;
foreach ($data as $row) {
if (empty($header)) {
$header = array_keys($row);
fputcsv($fp, $header);
$header = array_flip($header);
}
fputcsv($fp, array_merge($header, $row));
}
fclose($fp);
return;
}
Above code is working for below json
[
{
"Id": "1",
"Name": "Juned Ansari",
"Position": "Full Stack Developer",
"Salary": "$99999"
},
{
"Id": "2",
"Name": "Mayur Marolia",
"Position": "Data Analyst",
"Salary": "$6789000"
},
{
"Id": "3",
"Name": "Mitesh Panchal",
"Position": "Team Leader",
"Salary": "$2324540"
}
]
but the problem is if my json structure changed then i have to rewrite above function like it is not working for below json
[
{
"BILLING_SOFTWARE_API_KEY": "ABCD1234",
"DISTRIBUTOR_API_KEY": "11380",
"SALESMANS": [
{
"sm_code": 1,
"sm_name": "DEEPAK MEHTA 7044524144"
},
{
"sm_code": 2,
"sm_name": "Juned Ansari"
}
]
}
]
The problem is that JSON is unstructured, while CSV is structured.
To clear this hurdle you must first of all gather all the JSON fields in all the structure, and since the header must be written first, you need to cycle through the JSON twice.
$columns = [ ];
// This could be a foreach
// foreach($data as $row) { $columns = array_merge($columns, array_keys($row)); }
array_map(function($row) use (&$columns) {
$columns = array_unique(array_merge($columns, array_keys($row)));
}, $data);
// Now columns contain all columns in all rows of the JSON.
$fp = fopen($cfilename, 'w');
fputcsv($fp, $columns);
// Set all empty fields to some default
$template = array_fill_keys($columns, '');
foreach ($data as $row) {
fputcsv($fp, array_values(array_merge($template, $row)));
}
fclose($fp);
The above will not function out of the box for complex data (if a column has sub-information, like in your example). There you need a more complex step:
foreach ($data as $row) {
$collapsed = array_map(function($value) {
if (is_array($value)) {
return implode(', ', $value);
}
return $value;
}, $row);
fputcsv($fp, array_merge($template, $collapsed));
}
Still more complex information in the JSON is a clear indication that you're doing this wrong. Your best bet is then to re-encode the complex value as JSON and store it as is in the CSV field (use json_encode() instead of implode, above).
The Great Column Name Massacre
For those cases where you need to throw bad money after worse, you can implement what I called the Great Column Name Massacre. In its easiest form, you code
{
"address": {
"street": "Piazza Vieusseux",
"number": 2,
"locality" : {
"type": "city",
"name": "Florence"
}
}
}
as
[
"address_street" => "Piazza Vieusseux",
"address_number" => 2,
"address_locality_type" => "city",
"address_locality_name" => "Florence"
]
I'm feeling of two minds about this. Please do not take this wrong, but I'm feeling sort of like you asked me why your Smith&Wesson battery-operated hair dryer is not working, even if you put all six batteries in the drum, pointed it to your head and pulled the trigger.
And I feel like I'm telling you "Oh, there's a safety switch on the side. You need to move it from SAFE to FIRE, or it will not work".
So bearing in mind that this looks like a very bad idea, the folding function I mentioned in the comments is this (you can adapt it to your needs, see later):
function fold($arry, $prefix = '') {
$retval = [ ];
foreach ($arry as $key => $value) {
$newkey = $prefix.$key;
if (is_array($value)) {
$folded = fold($value, $newkey . '_');
foreach ($folded as $subkey => $subval) {
$retval[$subkey] = $subval;
}
} else {
$retval[$newkey] = $value;
}
}
return $retval;
}
Once each element of the array has been folded, it can be analyzed to find out the column names (you can do this while folding) and then everything proceeds like above.
Testing
The folding function works properly with the provided JSON sample, and yields
Array
(
[BILLING_SOFTWARE_API_KEY] => ABCD1234
[DISTRIBUTOR_API_KEY] => 11380
[SALESMANS_0_sm_code] => 1
[SALESMANS_0_sm_name] => DEEPAK MEHTA 7044524144
[SALESMANS_1_sm_code] => 2
[SALESMANS_1_sm_name] => Juned Ansari
)
This of course immediately raises the first problem; "DISTRIBUTOR_API_KEY" is what we would expect from {"DISTRIBUTOR": {"API": {"KEY": 11380}}}. It works, but the decoding is ambiguous.
To overcome this limitation the quickest way is to change the delimiter from '_' to something else, or encode it differently in the keys.
Be warned: there will be no end of problems with this approach. If I had the time, I flatter myself fantasizing that I might end up with a post to rival the Famous Answer.
Having not the time, I hereby decline all responsibility for the frightful damage, loss of property, loss of productivity, loss of time, dereliction of duty, alienation of spouse and family ties and dire health consequences (included, but not limited to, a painful and prolonged death) that I believe are sure to follow.
I use simple client SIDE to convert JSON/HTML/XML to CSV,EXCEL...
because it is easy to download by attaching the file to download attribute of anchor tag...
here is an example you may like ...
The JS FIDDLE
$(document).ready(function(){
$('button').click(function(){
var data = $('#txt').val();
if(data == '')
return;
JSONToCSVConvertor(data, "Vehicle Report", true);
});
});
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
//Set Report title in first row or line
CSV += ReportTitle + '\r\n\n';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData[0]) {
//Now convert each value to string and comma-seprated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
//Generate a file name
var fileName = "MyReport_";
//this will remove the blank-spaces from the title and replace it with an underscore
fileName += ReportTitle.replace(/ /g,"_");
//Initialize file format you want csv or xls
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
// Now the little tricky part.
// you can use either>> window.open(uri);
// but this will not work in some browsers
// or you will not get the correct file extension
//this trick will generate a temp <a /> tag
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}

PHP foreach not saving all data from JSON

I'm pulling data from JSON array in php.
Everything works as expected but somewhere in the loop parts gets lost, it only pulls first one.
Please help.
Thank you very much.
Here is Json:
$json = '
{
"theId": "fB17",
"loadId": "82387T",
"description": "Short description",
"contact": "Name of person",
"contactinfo": "Phone number or email of contact person",
"pickupaddress": "Address",
"parts": [
{ "number": "655-2032B" },
{ "number": "655-2056" },
{ "number": "655-2056" },
{ "number": "300-85091" }
]
}';
PHP code:
$data = json_decode($json);
$theId .= $data->theId;
$loadId .= $data->loadId;
$description .= $data->description;
$contact .= $data->contact;
$contactinfo .= $data->contactinfo;
$pickupaddress .= $data->pickupaddress;
ALL ABOVE GET PULLED FROM JSON AND SAVED PROPERLY
Saving data
$obj = new ElggObject();
$obj->subtype = "load";
$obj->description = strip_tags($description);
$obj->title = $title.$theId.'-'.$loadId;
$obj->contact = $contact;
$obj->contactinfo = $contactinfo;
$obj->pickupaddress = $pickupaddress;
$guid = $obj->save();
Object is saved with basic info
Now going through "parts" data from Json
foreach ($data->parts as $core_title) {
// Getting "parts' value from Json
$titlename = $core_title->number;
//Now need to use that data and find existing entity with that title in Database
$dbprefix = elgg_get_config('dbprefix');
$options['joins'][] = "JOIN {$dbprefix}objects_entity oe ON oe.guid = e.guid";
$options['wheres'][] = "oe.title = '$titlename'";
$options['types'] = array('object');
$options['subtypes'] = array('core');
$options['limit'] = 1;
$entity = elgg_get_entities($options);
// I got that entity that matches the title
//Now get GUID of the entity
foreach ($entity as $o) {
$boxg = $o->guid;
}
// It works I get the GUID as $boxg but now need to save EACH $data->parts as annotation to database
$obj->annotate('cores', $boxg);
}
IT only grabs first one fron Json ( 655-2032B )and saves only that one.
If I do this it saves each $data->parts value not just first one:
foreach ($data->parts as $core_title) {
$titlename = $core_title->number;
$obj->annotate('cores', $titlename);
}
This code makes no sense:
//Now get GUID of the entity
foreach ($entity as $o) {
$boxg = $o->guid;
}
It goes through all items in $entity and keeps overwriting $boxg value without actually doing anything with the value.
The result of this foreach loop is that $boxg holds the GUID of the last item in $entity and only then this one single value used to annotate:
$obj->annotate('cores', $boxg);
Is this what you really wanted to do? Shouldn't the annotate method be used inside the foreach loop?
Apart from that it's hard to give you a clear answer because your code is rather obscure and not well explained.
Figured it out finally.
It was not foreach but what was in it.
Ended up making function that does database query to find existing entity with that title.
This is what I ended up with.
Thanks everyone for the help.
foreach ($data->parts as $core_title) {
$titlename = $core_title->number;
$entity = get_object_by_title('core',$titlename);
foreach ($entity as $o) {
$coreguidd = $o->guid;
$obj->annotate('cores', $coreguidd);
}
}

Categories