CodeIgniter: Select the same like parameter on JSON list - php

I'm trying to use tokeninput from jQuery Token input, but the data is from the API. I already got the data from API and made a JSON list (see below).
When a user inputs in my token input, it will select from the JSON list, like user/auto_unit?queryParam=q for example. It already gets the user input correctly, but it still returns all data, even those that do not match the user input.
What I want is when the user searches for "Sosiologi", the only values that would show are those string which have "sosiologi" in them.
Is it possible to get only the same values and how can I do that? Thanks in advance!
My JSON list:
// 20170401095401
// http://exp.uin-suka.ac.id/aspirasi/user/auto_unit?queryParam=Filsafat%20Agama
[
{
"id": "UA000001",
"name": "Filsafat Agama"
},
{
"id": "UA000002",
"name": "Perbandingan Agama"
},
{
"id": "UA000003",
"name": "Ilmu Al-Qur'an dan Tafsir"
},
{
"id": "UA000004",
"name": "Sosiologi Agama"
},
{
"id": "UA000005",
"name": "Matematika"
},
{
My JSON code to get the list
function auto_unit() {
$data['unit'] = $this->m_simpeg->getAllUnit();
foreach ($data['unit'] as $key ){
$row['id']= $key['UNIT_ID'];
$row['name']= $key['UNIT_NAMA'];
$row_set[] = $row;
}
echo json_encode($row_set);
}
Model to get API M_simpeg.php:
public function getAllUnit(){
return $this->s00_lib_api->post_api(
1001, 1, null,
URL_API_SIMPEG.'simpeg_mix/data_view'
);
}

Check your server side code as it is not filtering the array.
Codeigniter sample code
<?php
function filter(){
$queryParam=$this->input->get('queryParam');
$res=$array.filter($queryParam);
return $res;
}
?>

Related

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.

Zoho - Get json value from returned data

I'm using zoho crm..
I get the json data below returned from a query
however I'm struggling to get the value of a string inside the returned data
Here is a sample of the data returned
"response": {
"result": {
"Deals": {
"row": {
"no": "1",
"FL": [
{
"val": "DEALID",
"content": "3508588000000206039"
},
{
"val": "SMOWNERID",
"content": "3508588000000176021"
},
{
"val": "Amount",
"content": "5000"
}
I'm trying to get the Amount value
Here is the PHP code
$json = file_get_contents($url);
$obj = json_decode($json);
$amount = $obj->result->Deals->row->FL['Amount'];
echo 'Deal Amount : £'.$amount;
Thanks In Advance
You need to change a bit
$amount = $obj->response->result->Deals->row->FL[2]->content;
//--------------^index------------------------^index---^column name need to be correct---
Dealing with Zoho response could get messy. You could use this library to help smoothen things for you.
In the meantime, $obj->response->result->Deals->row->FL[2]->content; should do the trick for you.

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