create embedded json for autocomplete - php

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)

Related

Rearrange each key as object into an object of keys

So I can't exactly spot what I am doing wrong here, so I'm hoping the community could give me a boost so I can figure out exactly what is causing this.
I have the following foreach where I'm setting a bunch of objects into an array of objects.
$result = [];
foreach($items as $item) {
$result[] = ['id' => $item->get_id()];
$result[] = ['media_type' => $item->get_media_type()];
}
var_dump($result);
With the above code, I am getting the following output on var_dump($result);:
[
{
"id": "17992874035441353"
},
{
"media_type": "CAROUSEL_ALBUM"
},
{
"id": "17842233125750202"
},
{
"media_type": "IMAGE"
}
]
Here is what I am aiming for:
[
{
"id": "17992874035441353",
"media_type": "CAROUSEL_ALBUM"
},
{
"id": "17842233125750202",
"media_type": "IMAGE"
},
]
Could someone spot what might be going on with how I'm formatting the foreach and setting up the new array? I've tried multiple different things and can't seem to figure out the answer.
Every time you do: $result[] = ..., you're pushing a new array element into the array. You need to push all the data as one single array:
foreach($items as $item) {
$result[] = [
'id' => $item->get_id(),
'media_type' => $item->get_media_type(),
];
}

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

Populate PHP associative array using loop with mysql data

I'm creating simple PHP for output data to apexcharts javascript charts. To make apexcharts usable output I need to provide x and y value of the graphs as JSON. below code, I wrote to output the expected JSON.
$data_arr = array();
global $mysqli_conn;
$result = $mysqli_conn->query("sql");
$sql_out = array();
$sql_out = $result->fetch_all(MYSQLI_ASSOC);
$num_rows = mysqli_num_rows($result);
if ($num_rows < 1){
echo "zero";
}else{
foreach($sql_out as $item) {
$data_arr['x'][] = $item['time'];
$data_arr['y'][] = $item['status_code'];
}
}
$test_arr = array(
array(
"name"=>"lock",
"data"=>array($data_arr),
)
);
echo json_encode($test_arr);
my expected json output is like below
[
{
"name": "lock",
"data": [
{
"x": "2019-05-30 07:53:07",
"y": "1470"
},
{
"x": "2019-05-29 07:52:27",
"y": "1932"
}
]
}
]
But when I request data from my code what I'm getting something like this
[
{
"name": "lock",
"data": [
{
"x": [
"2019-05-30 07:53:07",
"2019-05-29 07:52:27",
"2019-05-26 15:46:56",
"2019-05-25 07:39:24"
],
"y": [
"1470",
"1932",
"1940",
"1470"
]
}
]
}
]
How can I create my expected JSON result from PHP code?.
You're creating them on a seprate space. When you declare and push them, put them on one container:
foreach ($sql_out as $item) {
$data_arr[] = array(
'x' => $item['time'],
'y' => $item['status_code']
);
}
When you do this:
$data_arr['x'][] = $item['time'];
$data_arr['y'][] = $item['status_code'];
They are on a separate containers, x and y containers, therefore you get the wrong format, like the one you showed.
When you declare them as:
$data_arr[] = array(
'x' => $item['time'],
'y' => $item['status_code']
);
You're basically tellin to push the whole sub batches but together.

Create 2D-Array from mysql query in php

I have this following result in my query:
I'm trying to create an array like this in php:
[
{
"software_version": "1.0",
"version_date": "10/08/2016",
"changelog": [
{
"type": "IMP",
"description": "Initial version."
}
]
},
{
"software_version": "1.0.1",
"version_date": "27/07/2017",
"changelog": [
{
"type": "ADD",
"description": "HostPanel update manager."
},
{
"type": "ADD",
"description": "Hook OnDaemonMinute."
}
]
}
]
I need to combine the result with the software_version row.
Any help is appreciated.
My php code:
$changelog = array();
foreach ($result as $r) {
$changelog[] = array(
'software_version' => $r['software_version'],
'version_date' => $r['version_date'],
'changelog' => array(
array(
'type' => 'IMP', // help
'description' => 'Initial version.'
)
)
);
}
The key is to use the software version as a key in $changelog as you build it.
$changelog = array();
foreach ($result as $r) {
// get the version (just to make the following code more readable)
$v = $r['software_version'];
// create the initial entry for the version if it doesn't exist yet
if (!isset($changelog[$v]) {
$changelog[$v] = ['software_version' => $v, 'version_date' => $r['version_date']];
}
// create an entry for the type/description pair
$change = ['type' => $r['type'], 'description' => $r['description']];
// add it to the changelog for that version
$changelog[$v]['changelog'][] = $change;
}
You'll need to use array_values to reindex $changelog before JSON encoding it in order to produce the JSON array output you're going for.
$changelog = array_values($changelog);

Convert PHP array to JSON using multi dimentional arrays

I am trying to convert this php array to a json. This is my code:
$c = array();
$c = array(
$c['cronjobs'] = array(
'id'=>1189515,
'groupId'=>12379,
),
);
$json = json_encode($c);
echo $json;
This is the output I'd like to acieve:
{"cronjobs":[{"id":1186437,"groupId":12379]}
Though using the above code this is what I am getting
[{"id":1189515,"groupId":12379}]
The [{"cronjobs"part is not appearing.
I'm not sure what I'm doing wrong.
This should get the result that you want (just wrap an array around the id, groupId array):
<?php
$c = array();
$c['cronjobs'] = array(array(
'id'=>1189515,
'groupId'=>12379,
));
echo json_encode($c);
// result {"cronjobs":[{"id":1189515,"groupId":12379}]}
?>
This is how you need to format your array:
$c = array(); // declare the array
$c['cronjobs'] = array( // populate the array
'id'=>1189515,
'groupId'=>12379,
);
$json = json_encode($c); // json_encode it
echo $json;
There is no need for $c = array($c['cronjob']); (which was what you were doing).
I think this is what you're looking for:
$c = array('cronjobs' => array());
$c['cronjobs'][] = array('id' => 1189515, 'groupId' => 12379);
//$c['cronjobs'][] = array('id' => 1234, 'groupId' => 4321);
$json = json_encode($c);
echo $json;
Cronjobs needs to contain an array of cronjob objects/arrays
Could also be written using one statement, like this:
$c = array('cronjobs' => array(
array('id' => 1189515, 'groupId' => 12379),
array('id' => 1234, 'groupId' => 4321)
));
Your problem is that in PHP array is used to represent both JSON objects and JSON lists hence the confusion. Consider the following code:
$cronjob = array(
'id' => 1189515,
'groupId' => 12379
);
echo json_encode($cronjob);
// {"id":1189515,"groupID":12379"}
As you can see this represents a single object. So we'll create a list of objects:
$cronjobs = array($cronjob);
echo json_encode($cronjobs);
// [{"id":1189515,"groupID":12379"}]
This is now a list as expected. Now the parent object:
$c = array(
'cronjobs' => $cronjobs
);
echo json_encode($c);
// {"cronjobs":[{"id":1189515,"groupID":12379"}]}
In JSON there is a name: value pair system
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
}
],
"children": [],
"spouse": null
}
if you want to achieve like {"cronjobs":[{"id":1186437,"groupId":12379]} then the array must be named like the following in PHP:
$c['cronjobs'] = array(
'id'=>1189515,
'groupId'=>12379,
);
$json = json_encode($c);
echo $json;

Categories