getting required json formatting - php

Hi friends i'm getting json from server (using kohana framework 3.0) like this....
{
"aaData": [
{
"regNo": "1",
"regDate": "2025-05-12",
"patientName": "Ratna",
"address": "saasgasgasga",
"city": "Hyderabad",
"phno": "2147483647",
"mrgStatus": "single",
"religion": "1",
"gender": "male",
"fathername": "Yohan",
"status": "2",
"age": "25"
}
]
}
but i want below format
{
"aaData": [
[
"1",
"2025-05-12",
"Ratna",
"saasgasgasga",
"Hyderabad",
"2147483647",
"single",
"1",
"male",
"Yohan",
"2",
"25"
]
]
}
kohana controller is
public function action_index()
{
$table = new Model_patientdetails();
$log =$table ->get_all();
$output = array("aaData" => $log);
$this->auto_render=false;
echo json_encode($output);
}
please suggest me how to get required json format
Thanks in advance

Use array_values() for get the values only
public function action_index()
{
$table = new Model_patientdetails();
$log =$tab ->get_all();
foreach($log as &$l)
{
$l = array_values($l)
}
$output = array("aaData" => $log);
$this->auto_render=false;
echo json_encode($output);
}

I haven't found $log1 variable at your code, so I think it was $log.
You can do it in this way:
public function action_index()
{
$table = new Model_patientdetails();
$log = $tab->get_all();
$output = array("aaData" => array_values($log));
$this->auto_render=false;
echo json_encode($output);
}

Related

Append an object to a JSON file with a correct format

In a Symfony project, I have a user-contacts.json file which contains :
[
{
"id": 137,
"userName": "testUserName",
"userEmail": "test#email.com",
"userQuestion": "This is my question ?",
"solved": false
}
]
In a service, I'm receiving an object coming from a symfony form, here is the content:
ContactFile.php on line 18:
App\Entity\Contact {#561 ▼
-id: 146
-userName: "Contact"
-userEmail: "test#test.com"
-userQuestion: "test ?"
-solved: false
}
I'd like to append this contact query to the user-contacts.json file, in a way that the user-contacts.json content has a valid JSON format, like so for example:
[
{
"id": 137,
"userName": "testUserName",
"userEmail": "test#email.com",
"userQuestion": "This is my question ?",
"solved": false
},
{
"id": 138,
"userName": "anotherUserName",
"userEmail": "another#email.com",
"userQuestion": "This is another question ?",
"solved": false
}
]
Unfortunately, here is my result right now:
[
[
{
"id": 148,
"userName": "anotherUserName",
"userEmail": "another#email.com",
"userQuestion": "Another question?",
"solved": false
}
],
{
"id": 149,
"userName": "test",
"userEmail": "test#test.com",
"userQuestion": "Question ?",
"solved": false
}
]
Here is my service code:
<?php
namespace App\Service;
use App\Entity\Contact;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Serializer\SerializerInterface;
class ContactFile
{
public function __construct(private Filesystem $filesystem, private SerializerInterface $serializer) {}
public function writeContactFile(Contact $contact): void
{
$actualFileContent = file_get_contents('../user-contacts/user-contacts.json');
$requestContent = $this->serializer->serialize($contact, 'json');
$array[] = json_decode($actualFileContent, true);
$array[] = json_decode($requestContent, true);
$result = json_encode($array, JSON_PRETTY_PRINT);
$this->filesystem->remove(['file', '../user-contacts/', 'user-contacts.json']);
$this->filesystem->appendToFile('../user-contacts/user-contacts.json', $result);
}
}
How would you append this "Contact" object to the user-contacts.json file, while having a standard JSON format?
As Cbroe said:
I replaced $array[] = json_decode($actualFileContent, true); to $array = $actualFileContent;
And now it's working. Thank you.

How to Delete Single item or Array From Session Main Array

Controller: for get data from session
public function SessionDestroy(Request $request)
{
if ($request->session()->has('data')) {
return $request->session()->get('data');
} else {
return "No Data";
}
}
this is session data i have and i want remove a single array:
[
{
"app_date": "2022-03-16",
"department": "2",
"doctor": "4",
"fee": "150"
},
{
"app_date": "2022-03-17",
"department": "2",
"doctor": "4",
"fee": "150"
},
{
"app_date": "2022-03-16",
"department": "2",
"doctor": "4",
"fee": "150"
}
]
So, How can i remove a single Array or Item
you don't have a unique id in your session to remove by this unique id ..
this may help you !
public function SessionDestroy(Request $request)
{
if (session()->has('data')) {
session()->forget('data');
if(!empty(request('app_date')) && is_array(request('app_date')))
$new_data = [];
$x = 0;
foreach(request('app_date') as $app_date){
$new_data[]['app_date'] = $app_date;
$new_data[]['department'] = request('department')[$x]??'';
$new_data[]['doctor'] = request('doctor')[$x]??'';
$new_data[]['fee'] = request('fee')[$x]??'';
}
session()->put('data', $new_data);
return session('data');
} else {
return "No Data";
}
}

Why does my php function not get data from JSON array?

I have a page that pulls information about TV shows from the TMDB as a json array with the help of the TMDB-API Wrapper. I am trying to get the page to display information on a tv shows's ['network'].
I have written a function for this that loops through the network array but I can't get it to work. Can anyone tell me what I'm doing wrong? Thanks.
This is my function that does not work.
//Get networks
public function getNetworks() {
$networks = array();
foreach($this->_data['networks'] as $data){
$networks[] = new Network($data, $this->getName());
}
return $networks;
}
Display.php
//Call the function and loop though results
echo ' <li>Networks: <ul>';
$networks = $tvShow->getNetworks();
foreach($networks as $network){
echo '<li>'. $network->getID() .'</li>';
}
This does work (written in the wrapper not me)
public function getSeasons() {
$seasons = array();
foreach($this->_data['seasons'] as $data){
$seasons[] = new Season($data, $this->getID());
}
return $seasons;
}
This does work
//Get Network
public function getNetworks() {
return $this->_data['networks'][0]['name'];
}
And then on display.php
echo '<b>'. $tvShow->getNetworks() .'</b>';
This is the json array
{
"backdrop_path": "/c8A5IYqIT1ez15sqA8wX5tCDTmF.jpg",
"created_by": [
{
"id": 1187819,
"name": "Matthew Weiner",
"profile_path": null
}
],
"episode_run_time": [
47,
45
],
"first_air_date": "2007-07-19",
"genres": [
{
"id": 18,
"name": "Drama"
}
],
"homepage": "http://www.amc.com/shows/mad-men",
"id": 1104,
"in_production": false,
"languages": [
"en"
],
"last_air_date": "2015-05-17",
"name": "Mad Men",
"networks": [
{
"id": 174,
"name": "AMC"
}
],
Tvshow Class
class TVShow{
//------------------------------------------------------------------------------
// Class Variables
//------------------------------------------------------------------------------
private $_data;
/**
* Construct Class
*
* #param array $data An array with the data of the TVShow
*/
public function __construct($data) {
$this->_data = $data;
}

Remove model name from json array in cakephp

I've set up a custom search action in my cakephp controller
public function search() {
$results = [];
$results['data'] = $this->Content->find('first',
array(
'conditions' => array($this->request->params['pass'][0] . ' like' => "%" . $this->request->params['pass'][1] . "%")), array('contain' => false)
);
if(count($results['data'])>0){
$results['success'] = true;
$this->set(compact('results'));
$this->set('_serialize', array('results'));
}
else{
$results['success'] = false;
}
}
The issue I'm running into is that the rest of my API formats data like this:
{
"success": true,
"data": [
{
"id": "5509be6c-9ef8-42c3-af39-2d492773a233",
"title": "test2",
},
{
"id": "5509be6c-9ef8-42c3-af39-2d492773a233",
"title": "test1"
}
]
}
but what I'm getting from cakephp right now for my search action is this:
{
"results": {
"success": true,
"data": {
"Content": {
"id": "52efcbeb-e984-4a2e-b76f-0cc34056922c",
"title": "Homeasdfasdf",
}
}
}}
How do I get rid of the extra "results" array wrapper so that my data is coming out in the same format?
Use the current() php function. In your controller make
$results = current($results);
before the set() call

PHP Array strange behavior

I am using a PHP Class that is generating a nested categories tree menu in json format from a MySQL database. The problem is that the array used to fill the data doesn't do what it is supposed to
The PHP Class is:
class nestedCategories {
public $json = array();
public function generateMenu($categories,$level){
$this->json = array();
foreach($categories as $category ){
$this->json['title'] = $category->description;
$this->json['expanded'] = true;
if(isset($category->children) && count($category->children)>0){
$this->json['folder'] = true;
$this->json['children'] = $this->generateMenu($category->children,$category->category_id);
} else {
$this->json['folder'] = false;
}
}
}
public function getJSON() {
return $this->json;
}
The $json is supposed to look like:
[
{"title": "Animalia", "expanded": true, "folder": true, "children": [
{"title": "Chordate", "folder": true, "children": [
{"title": "Mammal", "children": [
{"title": "Primate", "children": [
{"title": "Primate", "children": [
]},
{"title": "Carnivora", "children": [
]}
]},
{"title": "Carnivora", "children": [
{"title": "Felidae", "lazy": true}
]}
]}
]},
{"title": "Arthropoda", "expanded": true, "folder": true, "children": [
{"title": "Insect", "children": [
{"title": "Diptera", "lazy": true}
]}
]}
]}
]
but, when I am trying to pull the data from MySQL, the $json array only gives me the last pulled data from MySQL, as if it is erasing all data behind
Could someone talk me trough?
You are overwriting the array with each loop around categories, and wiping out the member variable with an array assignment each time round.
Plus, I suspect that it won't return the structure you're looking for unless you make it preoperly recursive (which means returning the array that you've built):
class nestedCategories {
public function generateMenu($categories,$level){
$categoriesJson = array();
foreach($categories as $category ){
$categoryJson = array();
$categoryJson['title'] = $category->description;
$categoryJson['expanded'] = true;
if(isset($category->children) && count($category->children)>0){
$categoryJson['folder'] = true;
$categoryJson['children'] = $this->generateMenu($category->children,$category->category_id);
} else {
$categoryJson['folder'] = false;
}
$categoriesJson[] = $categoryJson;
}
return $categoriesJson;
}
}
You would now just get back the data by calling generateMenu rather than using the member variable.
You are setting $this->json = array(); at the top of your generateMenu method. When you make the recursive call it destroys what was written to the array on the previous call.
In addition in each recursive call $this->json['title'] will over write the previous title. The same goes for expanded, children and folder.
It looks like I took a little longer that I should have to make the example code. Here it is anyway.
class Foo {
public function generateMenu($categories){
$json_array = array();
foreach($categories as $category) {
$json_object = array();
$json_object['title'] = $category->description;
if(isset($category->children) && count($category->children)>0){
// it looks like expanded should only be
// in objects with > 0 children
$json_object['expanded'] = true;
$json_object['folder'] = true;
$json_object['children'] = $this->generateMenu($category->children);
} else {
// based on the json in the question it looks like
// it should always contain a children array, but no folder element
$json_object['children'] = array();
}
$json_array[] = $json_object;
}
return $json_array;
}
}
Here is the test data:
$Diptera = new stdClass();
$Diptera->description = 'Diptera';
$Insect = new stdClass();
$Insect->description = 'Insect';
$Insect->children = array($Diptera);
$Arthropoda = new stdClass();
$Arthropoda->description = 'Arthropoda';
$Arthropoda->children = array($Insect);
$Felidae = new stdClass();
$Felidae->description = 'Felidae';
$Carnivora2 = new stdClass();
$Carnivora2->description = 'Carnivora';
$Carnivora2->children = array($Felidae);
$Carnivora = new stdClass();
$Carnivora->description = 'Carnivora';
$Primate2 = new stdClass();
$Primate2->description = 'Primate';
$Primate = new stdClass();
$Primate->description = 'Primate';
$Primate->children = array($Primate2, $Carnivora);
$Mammal = new stdClass();
$Mammal->description = 'Mammal';
$Mammal->children = array($Primate, $Carnivora2);
$Chordate = new stdClass();
$Chordate->description = 'Chordate';
$Chordate->children = array($Mammal);
$Animalia = new stdClass();
$Animalia->description = 'Animalia';
$Animalia->children = array($Chordate);
$catagories = array($Animalia);
Here is how it's called:
$f = new Foo();
echo json_encode($f->generateMenu($catagories), JSON_PRETTY_PRINT);
Here is the output:
[
{"title": "Animalia", "expanded": true, "folder": true, "children":
[
{"title": "Chordate", "expanded": true, "folder": true, "children":
[
{"title": "Mammal", "expanded": true, "folder": true, "children":
[
{"title": "Primate", "expanded": true, "folder": true, "children":
[
{"title": "Primate", "children": []},
{"title": "Carnivora", "children": []}
]
},
{"title": "Carnivora", "expanded": true, "folder": true, "children":
[
{"title": "Felidae", "children": []}
]
}
]
}
]
},
{"title": "Arthropoda", "expanded": true, "folder": true, "children":
[
{"title": "Insect", "expanded": true, "folder": true, "children":
[
{"title": "Diptera", "children": []}
]
}
]
}
]
}
]
You are overwriting the array keys when you iterate over the JSON.
$array = array();
$array['foo'] = 'bar';
//$array['foo] = 'bar';
$array['foo'] = 'foo';
//$array['foo'] = 'foo';

Categories