how to change the format of json value data in codeigniter - php

I am trying to display data for a plugin with a predefined json format, but after I try the data does not match the format how the problem?
JSON Required
[
{
latLng: [-6.17343444,1206.834234294],
name: 'XY'
},
{
latLng: [-6.1742343244,106.898987294],
name: 'XK'
}
]
Result my JSON
[
{
"latLng": "-6.17343444,1206.834234294",
"name": "XK"
},
{
"latLng": "-6.1742343244,106.898987294",
"name": "XY"
}
]
myscript PHP
public function lat_lang() {
foreach($this->model->name_model() as $row){
$data[] = array(
'latLng' => $row->lat_long,
'name' => $row->city
);
}
header('content-type: application/json');
echo json_encode($data);
}
call JSON
$.parseJSON('<?php echo base_url().'mycontrollers';?>', function(datas) {
console.log(datas);
});

You can use explode() to transform the string "-6.17343444,1206.834234294" into an array [-6.17343444,1206.834234294]:
public function lat_lang() {
foreach($this->model->name_model() as $row){
$data[] = array(
'latLng' => explode(',',$row->lat_long),
'name' => $row->city
);
}
header('content-type: application/json');
echo json_encode($data);
}
If you want to get floats (for all value in the JSON), you could use JSON_NUMERIC_CHECK:
json_encode($data, JSON_NUMERIC_CHECK);
Or, just for a specific value:
$latLng = explode(',', $row->lat_long);
$latLng = array_map('floatval', $latLng);
$data[] = array(
'latLng' => $latLng,
'name' => $row->city
);

Related

Change response format of REST API

I'm working on my REST API responses with PHP.
Here is my backend that generates the responses:
$query = $this->db->query("SELECT some_params from some_table ");
$result = $query->result();
foreach($result as $row){
$obj[] = array(
'title' => $row['title'],
'price' => $row['price'],
);
}
print_r(json_encode($obj));
and with that I have the following response: an array of json objects
[
{
"title":"Marketing",
"price":"0"
},
{
"title":"SAP B1",
"price":"10"
}
]
What I would like to do is return a new object, something like this:
{
"apiVersion": "2.0",
"data": {
{
"title":"Marketing",
"price":"0"
},
{
"title":"SAP B1",
"price":"10"
}
}
}
Does anyone have any idea how I could implement this? thanks!
You can easily have a class or function to do that for you. Some thing like below should help,
// provided you are using php > 7 . otherwise parmas
// can become $data, $apiversion ( without typecasting )
function api_reponse(array $data, string $apiVersion)
{
return json_encode([
'apiVersion' => $apiVersion,
'data' => $data
])
}
You can then use,
$query = $this->db->query("SELECT some_params from some_table ");
$result = $query->result();
foreach($result as $row){
$obj[] = array(
'title' => $row['title'],
'price' => $row['price'],
);
}
print_r( api_response($obj, '2.0') );

How to convert a PHP array into json string

I have a PHP array built with a while loop. I do successfully convert it to JSON string, however the output is not what I want and need some help to get it right:
My current code:
while(!$sql_query->EOF){
$data[] = array(
'id' => $id,
'name' => $name,
'title' => $title
);
$sql_query-> MoveNext(); }
echo json_encode($data);
The output I get with my code is this:
[
{
"id":"1",
"name":"Nick",
"title":"Office"
},
{
"id":"2",
"name":"Amy",
"title":"Home"
}
]
However, I need the outcome to be:
{
"data": [
[
"1",
"Nick",
"Office"
],
[
"2",
"Amy",
"Home"
]
]
}
I tired paying around with array_values() but no success so far.
Can somebody suggest the right approach here?
When building your array, don't add the keys to the values, this will allow the encoding to use array notation, then add the "data" key as part of the encode...
$data = [];
while(!$sql_query->EOF){
$data[] = [ $id, $name,$title];
$sql_query-> MoveNext();
}
echo json_encode(["data" => $data]);
If you do something like:
$result = (object)["data" => $data];
echo json_encode($data);
this will give you the output you require.
First of all you have to modify you array
$newData = [];
foreach($data as $item) {
$newData[] = array_values($item);
}
and then create new array
echo json_encode(["data"=>$newData])

create embedded json for autocomplete

I am using following code for making data coming from database as json format
public function employeeSearch()
{
$arrayOfEmployee = array();
$arrayToPush = array();
$arrayToJSON = array();
$new_item = $this->apicaller->sendRequest(array(
"controller" => "Employee",
"action" => "employeeSearch",
"searchCriteria" => "12345"
));
$arrayOfEmployee = json_decode($new_item,true);
foreach($arrayOfEmployee as $key => $employee)
{
$arrayToPush = array('data' => $employee['FullName'], 'value' => $employee['_id']['$oid']);
array_push($arrayToJSON, $arrayToPush);
}
echo json_encode($arrayToJSON);
}
The output is
[{"data":"Aasiya Rashid Khan","value":"5aa662b0d2ccda095400022f"},
{"data":"Sana Jeelani Khan","value":"5aa75d8fd2ccda0fa0006187"},
{"data":"Asad Hussain Khan","value":"5aaa51ead2ccda0860002692"},
{"data":"Ayesha Khan Khann","value":"5aab61b4d2ccda0bc400190f"},
{"data":"adhar card name","value":"5aaba0e1d2ccda0bc4001910"}
]
Now I want that json elements should look like
{
"suggestions": [
{
"value": "Guilherand-Granges",
"data": "750"
},
{
"value": "Paris 01",
"data": "750"
}
]
}
I have to implement this in jQuery autocomplete plugin...
Please help!!!
Replace the last line with
echo json_encode(["suggestions" => $arrayToJSON]);
This should result in the wanted result!
(This hold only true if you igonre the fact that the data in value and name is not the same/similar)

create style of JSON object with PHP

my JSON currently looks like this
{
"customers":
[
{
"customer_id":3,
"customer_name":"Rick",
"Address":"333 North Road"
},
{
"customer_id":4,
"customer_name":"Robby",
"Address":"444 North West Road"
}
]
}
and I would like it to look like this
{
"customers":
[
{
"customer":
{
"customer_id":3,
"customer_name":"Rick",
"Address":"333 North Road"
}
},
{
"customer":
{
"customer_id":4,
"customer_name":"Robby",
"Address":"444 North West Road"
}
}
]
}
It is being created in this php script but I'm unsure how to add the customer attribute to each JSON object programmtically. help please?
//populate results
$json = array();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$array = array(
'customer_id' => $row['CustomerID'],
'customer_name' => $row['Name'],
'Address' => $row['Address']
);
array_push($json, $array);
foreach ($row as $r) {
}
}
$jsonstring = '{"customers":'. json_encode($json). "}";
return $jsonstring;
//populate results
$json = array();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$array = array("customer" => array( // <-- change is here
'customer_id' => $row['CustomerID'],
'customer_name' => $row['Name'],
'Address' => $row['Address']
)
);
array_push($json, $array);
foreach ($row as $r) {
}
}
$jsonstring = '{"customers":'. json_encode($json). "}";
return $jsonstring;

PHP - Convert HTML ul list into json format

I would like to convert an HTML ul list into a json format.
The html list is in this format:
<li><span class="orgname">Adams Center Free Library</span> <span class="status">Closed</span></li>
<li><span class="orgname">Weight Watchers Watertown</span> <span class="status">Delayed</span></li>
I'd like it to be in a json format like this:
{
"meta": {
"closed_count": "1",
"delayed_count": "1"
},
"list": [
{
"data": {
"orgname": "Adams Center Free Library",
"status": "Closed"
}
},
{
"data": {
"orgname": "Weight Watchers Watertown",
"status": "Delayed"
}
}
]
}
Can someone help me out with this?
I assume you are outputting data from some database. So add values to array and than encode to json:
$delayed = 0;
$close = 0;
$data = [];
echo "<ul>";
foreach ($myArray as $row) {
echo "<li><span class='orgname'>{$row['orgname']}</span> <span class='status'>{$row['status']}</span></li>";
$data[] = ['data' => ['orgmane' => $row['orgname'], 'status' => $row['status']]];
// or if $row only has 'orgname' and 'status'
$data[] = ['data' => $row];
if (strtolower($row['status']) == 'delayed') {
$delayed++;
} else {
$closed++;
}
}
echo "</ul>";
json_encode(
[
'meta' => ['closed_count' => $closed, 'delayed_count' => $delayed],
'list' => $data,
]
);

Categories