Assign Json file objects to variables - php

I have a JSON file that I would like to use with PHP to assign variables to the individual objects.
The file looks like this: (Is this a valid JSON file?):
{"draw":0,
"data":[
["123456789",
"first_data_one",
"second_data_one",
"third_data_one",
"fourth_data_one",
"fith_data_one"],
["7656576657",
"first_data_two",
"second_data_two",
"third_data_two",
"fourth_data_two",
"fith_data_two"],
],
"recordsTotal":"181",
"recordsFiltered":"181"
}
I need some help assigning each values,
EX: number = "123456789", $first_data = "first_data_one", $second_data = "second_data_one", $third_data = "third_data_one", $fourth_data = "fourth_data_one", $fith_data = "fith_data_one" to variables.
In the end I want to echo each, some thing like this:
echo Number: $number;
echo Number: $first_data;
echo Number: $second_data;
echo Number: $third_data;
echo Number: $fourth_data;
echo Number: $fith_data;
I want to put it all in a table in the end.

Your table header contains names for columns
<thead>
<tr>
<th>Number</th>
<th>first_data</th>
<th>second_data</th>
<th>third_data.</th>
<th>fourth_data</th>
<th>fith_data</th>
</tr>
</thead>
one way is to define columns, but then your return object based , columns as key
$('#myjson').dataTable( {
"ajax": { "url": "api/data.json",
"dataSrc": "data" } , // default datasrc is data, so no need of it
"columns": [
{ "data": "number" },
{ "data": "first_data" },
{ "data": "second_data" },
{ "data": "third_data" },
{ "data": "fourth_data" },
{ "data": "fith_data" }
]
} );
this will automatically assign data to columns
the header will be your html header,
like you have 6 columns and your json also has 6 so it will be fine
$('#myjson').dataTable( {
"ajax": { "url": "api/data.json"}
} );
and if you switch on serverside processing
then you get these
"recordsTotal": 57, "recordsFiltered": 57,
have a look at the api docs

Related

How to get values from json object to php array

I am writing a php file for an application that allows the user to print a project report (with fpdf library).
The aim is to get datas from a db and then to build the PDF file dynamically.
The datas are stored in json.
It is ok for almost all datas, but there are some that I can't reach.
Here is an example :
First of all I already did this :
$Array['roof_coordinates'] = json_decode($Array['roof_coordinates'], false);
To get the number "nb" of "A523500" I'm doing like that :
$Array['roof_coordinates']->results->packingList->total->A523500->nb;
What am I doing wrong ?
"roofCoordinates": {
"results": {
"packingList": {
"total": {
"A523500": {
"ref": "STRA523500",
"nb": 16
},
"A523120": {
"ref": "STRA523120",
"nb": 0
},
"A522100": {
"ref": "STRA522100",
"nb": 8
},
},
}
},
}
And I tried to pass "true" to json_decode to convert objects to associative array but it doesn't seems to work...
Any help will be great !
Thank you in advance ;)
Make sure you are accessing the resulting data structure correctly, it should work whether you decode to an array or an object.
<?php
$json = <<<END
{
"roofCoordinates": {
"results": {
"packingList": {
"total": {
"A523500": {
"ref": "STRA523500",
"nb": 16
},
"A523120": {
"ref": "STRA523120",
"nb": 0
},
"A522100": {
"ref": "STRA522100",
"nb": 8
}
}
}
}
}
}
END;
$arrayResults = json_decode($json, true);
$nbFromArray = $arrayResults['roofCoordinates']['results']['packingList']['total']['A523500']['nb'];
$stdClassResults = json_decode($json);
$nbFromStdClass = $stdClassResults->roofCoordinates->results->packingList->total->A523500->nb;
assert($nbFromArray==16, 'Value should equal 16');
assert($nbFromArray==$nbFromStdClass, 'Values from either json_decode method should be equal');
echo 'From array: '.$nbFromArray.PHP_EOL;
echo 'From stdClass: '.$nbFromStdClass.PHP_EOL;

PHP JSON: Get value from siblings reference

I am working on a project that requires reading data from this terrible API that responds with terrible structured JSON data:
"finn-contanct": {...}
"finn-adata": {
"#attributes": {
"model": "https://cache.api.finn.no/iad/ad/model/car-used-sale"
},
"finn-field": [
{
"#attributes": {
"name": "authorized_dealership",
"value": "true"
}
},
{
"#attributes": {
"name": "body_type",
"value": "Stasjonsvogn"
}
},
{
"#attributes": {
"name": "car_location",
"value": "Norge"
}
},
{
"#attributes": {
"name": "engine"
},
"finn-field": [
{
"#attributes": {
"name": "effect",
"value": "90"
}
},
{
"#attributes": {
"name": "fuel",
"value": "Diesel"
}
}
]
},
{...},
]
}
How can i dynamically get the values under each attribute based on the siblings name value? Ideally with a function that accepts one parameter that finds the value in there by providing a key corresponding to the value i'm looking for.
Here is an example of what i'm expecting:
Given a function that expects one parameter: getAttrValue('key') I want to get the value under the #attributes sibling. So if I use the function like this: getAttrValue('body_type') i'm simply expecting this back: Stasjonsvogn. I don't really care about nested items. So if I do this: getAttrValue('fuel') I'm simply expecting: Diesel
I found this answer here on SO. But the problem with that method is that it doesn't work well with nested items. So does anyone have a method that would work with the data-structure I got above here?
The response is a total mess and I don't know how to handle it, nor how to Google it properly. So any help would be appreciated greatly.
Collect attributes into associative array recursively:
function collectAttributes($data)
{
$attributes = [];
$nodeAttribute = isset($data['#attributes']) ? $data['#attributes'] : [];
//collect current node attribute value
if (isset($nodeAttribute['name'])) {
$attributes[$nodeAttribute['name']] = isset($nodeAttribute['value']) ? $nodeAttribute['value'] : '';
}
//collect nested attributes recursively
foreach ($data as $nestedNode) {
if (is_array($nestedNode)) {
$attributes = array_merge($attributes, collectAttributes($nestedNode));
}
}
return $attributes;
}
And then use result as simple associative array:
$data = json_decode($inputJson, true);
$atttributes = collectAttributes($data);
echo $attributes['fuel']; //don't forget isset checking if you are not sure about content
But if you have attributes with same name you'll see only latest this way.

Accessing array inside array

I'm working on my task right now, which accessing specific array when it is called by front end.
My example data is like this
{
"data": [
{
"name": "Jon Snow",
"id": "01-0001",
},
{
"name": "Robert Stark",
"id": "01-0002"
},
{
"name": "Sansa Stark",
"id": "01-002333"
},
{
"name": "Arya Stark",
"id": "01-00012"
},
{
"name": "Bran Stark",
"id": "01-0003"
},
{
"name": "Rickon Stark",
"id": "01-0005"
}
]
}
* In my front end I have this code *
selectedEmployee: any=null;
setActiveEmployee(employee: any) {
this.selectedEmployee = employee;
let myJSON = JSON.stringify(this.selectedEmployee);
this.perEmpLateEarly();
}
Whenever I choose the employee i get the id of that employee.
So in this, if i choose "id": "01-0001" it will return the first array and it will keep the rest, and if I choose "id": "01-0002" it will return the second one and will keep the rest and so on. How can I do that in Php?
Thanks in advance
You will do a GET/POST HTTP request from frontend, which would look something like this in
your_backend_page.php?id=<ID HERE>
Then the "your_backend_page.php" would look like as follows:
$list = { "data": [ { .... }, { ... }] } // this is the array you have
$idFromFrontEnd = $_GET["id"];
foreach ($list["data"] as $item) { // iterate over all items
if ($item["id"] == $idFromFrontEnd) { // check if id matches
echo json_decode($item); // if matches, print this item
}
}
Please note this approach is okay if you have a small number of items. For a larger list, you might want to have a database, where you can use sql to select.

Decoding and looping through PHP JSON array

I have the following deocoded JSON array.
I need to access the "type" inside the context, as well as I need to loop through each of the values in the payload. How do I do that?
{
"RequestHeader":
{
"mess": "am putting it on my wall....",
"created_time": "2010-08-24T09:01:25+0000"
},
"context" :
{
"type": "friends,circles"
}
"payload" [ {12345},{12345} ,{2345} ]
}
I tried the following, but it doesn't work
$decoded = json_decode($json_string);
for ($i=0;$i<payload.length;++$i)
{
$id=$decoded->payload[$i];
//do some operation with the id
}
First of all the JSON you provided is invalid. Supposedly the valid one should look like this
{
"RequestHeader": {
"mess": "am putting it on my wall....",
"created_time": "2010-08-24T09:01:25+0000"
},
"context": {
"type": "friends,circles"
},
"payload": [
12345,
12345,
2345
]
}
After you've fixed the problem with JSON provider it will be quite easy to access data
<?php
$json = <<<'JSON'
{
"RequestHeader": {
"mess": "am putting it on my wall....",
"created_time": "2010-08-24T09:01:25+0000"
},
"context": {
"type": "friends,circles"
},
"payload": [
12345,
12345,
2345
]
}
JSON;
$data = json_decode($json, true);
$type = $data['context']['type'];
var_dump($type);
foreach($data['payload'] as $id) {
var_dump($id);
}
Remember to make sure you check that the data actually exists before accessing it, e.g. isset($data['context']['type']) unless you are absolutely sure in it's integrity.
When you use json_decode method, the output will be nested arrays
So for example to access context type you need to do the following
echo $decoded["context"]["type"];
And to loop on payload you need to do the following
for ($i=0;$i<$decoded["payload"].length;++$i)
{
$id=$decoded["payload"][$i];
//do some operation with the id
}

Datatable - JSON not being shown of size larger than 4KB

I am using data table to display data returned by a SQL Server 2008 procedure called in Codeigniter via Ajax($POST). Initially I made a very simple procedure with no input parameters, it only returns a list of JSON objects.
Below are my questions and my Codeigniter function returning JSON, AJAX function and JSON structure returned by my Codeigniter function:
1) JSON not returned for chunk larger than 4KB, it simply converts to HTML:
2) What if one of my procedure returns lets say 5000+ record and i want to display it in data table, is my way of doing it right? Or i should use some other best practices:
Codeigniter Function:
public function executeProc()
{
$sqlsrvr = $this->load->database('test', true);
// Get the input values of the procedure
$arr = array();
parse_str($_POST['str'],$arr);
//get Procedure Name
$procName = $_POST['procName'];
$sp ='exec secondProc';
$query = $sqlsrvr->query($sp);//->result();
$jawad = $query->result_array();
$this->output->set_header('Content-type: application/json');
echo json_encode($jawad);
}
AJAX Function
$(document).on('click','#executeProc',function(e){
$('#demo').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>');
e.preventDefault();
var jawad = $( ".jawad" ).serialize();
$.post('<?=base_url();?>command/executeProc',
{str:jawad,procName:$('#procName').val()},
function(html){
//loading data table on return
$('#example').dataTable( {
"data": html,
"columns": [
{ "data": "AppointmentID" },
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "AppointmentDate" }
]
} );
});
});
JSON Sample:
[
{
"AppointmentID": "1",
"FirstName": "Test",
"LastName": "test",
"AppointmentDate": "2013-01-12"
},
{
"AppointmentID": "2",
"FirstName": "dfg",
"LastName": "dfg",
"AppointmentDate": "2013-01-01"
}
]
-----AFTER EDIT------
STRANGE BEHAVIOR(JSON tab converts to HTML for larger records)
FOR 40 records that get displayed on data table
FOR records larger then 40 that don't get displayed on data table

Categories