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";
}
}
Related
I have flat array like:
[
{
"id": "1",
"parentId": "0",
"cost": 1000
},
{
"id": "2",
"parentId": "1",
"cost": 2000
},
{
"id": "3",
"parentId": "2",
"cost": 4000
},
...
]
Requirement:
convert flat array to tree array --> (DONE)
sum of each id is the total price of it and its child
now the problem appears:
should summation be done before or after converting from flat array to tree array
This is my code is try convert flat to tree:
public function buildTree(array $flat)
{
$grouped = [];
$fnBuilder = function ($companies) use (&$fnBuilder, $grouped) {
foreach ($companies as $k => $company) {
$id = $company['id'];
if (isset($grouped[$id])) {
$company['children'] = $fnBuilder($grouped[$id]);
}
$companies[$k] = $company;
}
return $companies;
};
return $fnBuilder($grouped[0]);
}
My expect result is like:
[
{
"id": "1",
"sum": 7000,
"children": [
{
"id": "2",
"sum": 6000,
"children": [
{
"id": "3",
"sum": 4000,
},
I wonder if it's possible to handle the summing inside the buildTree?
My idea is to have a tree and then handle the sum of sublevels, but i can't handle assigning the sum to the parent element
I created a class and incorporated your ideas.
class TreeBuilder {
private $flatArr;
private $idToNode;
public function __construct($flatArr) {
// Keep the flat arr in case we need it.
$this->flatArr = $flatArr;
// Create an array to lookup a node to determine if it exists.
$this->idToNode = array_combine(array_column($flatArr, 'id'), $flatArr);
}
public function buildTree() {
// create an empty array to hold root nodes
$roots = [];
// iterate through each node and add it to its parent's children list
foreach ($this->flatArr as &$node) {
$id = $node['id'];
$parentId = $node['parentId'];
if (isset($this->idToNode[$parentId])) {
$this->out("add child to $parentId " . print_r($node, true));
$parentNode = &$this->idToNode[$parentId];
if ( isset($parentNode['children']) ) {
$parentNode['children'] = [&$this->idToNode[$id]];
} else {
$parentNode['children'][] = &$this->idToNode[$id];
}
// $children[] = &$node;
} else {
$this->out("add to root " . print_r($node, true));
$roots[] = &$this->idToNode[$id];
}
}
// calculate the sum of each node and its children recursively
foreach ($roots as &$root) {
$this->calculateSum($root);
}
return $roots;
}
private function calculateSum(&$node) {
// calculate the sum of the current node
$node['sum'] = $node['cost'];
// recursively calculate the sum of the children nodes
$children = &$node['children'];
if (isset($children)) {
foreach ($children as &$child) {
$node['sum'] += $this->calculateSum($child);
}
}
return $node['sum'];
}
private function out($s) {
echo "$s\n";
}
}
You could build the tree without recursion, and then use recursion to update the sum, in post-order depth first order:
function buildTree(array $flat) {
foreach ($flat as ["id" => $id, "cost" => $sum]) {
$keyed[$id] = ["id" => $id, "sum" => $sum];
}
foreach ($flat as ["id" => $id, "parentId" => $parentId]) {
if (isset($keyed[$parentId])) {
$keyed[$parentId]["children"][] = &$keyed[$id];
} else {
$root = &$keyed[$id];
}
}
function updateSum(&$node) {
foreach ($node["children"] ?? [] as &$child) {
$node["sum"] += updateSum($child);
}
return $node["sum"];
}
updateSum($root);
return $root;
}
Example run:
$flat = json_decode('[
{
"id": "1",
"parentId": "0",
"cost": 1000
},
{
"id": "2",
"parentId": "1",
"cost": 2000
},
{
"id": "3",
"parentId": "2",
"cost": 4000
}
]', true);
$root = buildTree($flat);
print_r($root);
I wan to divide fetched a single column from database in three different columns.
The below code gives me one column image_url.
public function fetch()
{
$model = Image::select('image_url');
return Datatables::eloquent($model)->make(true);
}
I want to split this column into three columns before returning it.
as for now it is returned in this form..
{
"draw": 0,
"recordsTotal": 16,
"recordsFiltered": 16,
"data": [
{
"image_url": "public/uploaded_images/2019_08_27_WheatMaizeBanner_1.png"
},
{
"image_url": "public/uploaded_images/2019_08_27_WheatFlourBanner1.jpg"
},
{
"image_url": "public/uploaded_images/2019_08_27_TurDalBanner1.jpg"
},
{
"image_url": "public/uploaded_images/2019_08_27_TurBanner1.png"
}
]
}
But I want something like this
{
"draw": 0,
"recordsTotal": 16,
"recordsFiltered": 16,
"data": [
{
"image1": "public/uploaded_images/2019_08_27_WheatMaizeBanner_1.png",
"image2": "public/uploaded_images/2019_08_27_WheatFlourBanner1.jpg"
"image3": "public/uploaded_images/2019_08_27_TurBanner1.png"
}
]
}
try this:
public function fetch()
{
$model = Image::select('image_url');
$result = Datatables::eloquent($model)->make(true);
$data = [];
foreach($result->data as $i => $record) {
$data['image' . ($i+1)] = $record->image_url;
}
$result->data = [ (object)$data ];
return $result
}
I Have 2 table that I want to join them and fetch some data like this
I have one student with multiple grade
{
"student": {
"studentID": "2",
"Name": "s1",
"age": " 12",
"grade": [
{
"GradeID": "2"
},{
"GradeID": "3"
}
]
}
I fetch this data from two query in a function in my model and then use json_encode in my controller for my output
but I have this
{
"student": {
"studentID": "2",
"Name": "s1",
"age": " 12"
},
"grade": [
{
"GradeID": "2"
},{
"GradeID": "3"
}
]
}
and now I don't know how to use json_encode for the first format.
thanks
my model(student):
function get_student_id($id)
{
$student['student']=
$this->db->select('tbl_student.*')
->from('tbl_student')
->where('tbl_student.SID',$id)
->get()->row();
$student['grade']=
$this->db->select('tbl_grade.GradeID')
->from('tbl_grade')
->join('tbl_sudent','tbl_grade.StudentID=tbl_sudent.SID')
->where('tbl_student.SID',$id)
->get()->result();
return $student;
}
my controller:
public function get_student_id()
{
$id = $input['one'];
$this->load->model('student');
$temp=$this->student->get_student_id($id);
$output= json_encode($temp);
die($output);
}
You just have to structure the array you're returning from the model correctly. You're putting everything inside two subarrays called student and grade, which are inside the outer array student. Try this:
my model(student):
function get_student_id($id)
{
$student=
$this->db->select('tbl_student.*')
->from('tbl_student')
->where('tbl_student.SID',$id)
->get()->row();
$student['grade']=
$this->db->select('tbl_grade.GradeID')
->from('tbl_grade')
->join('tbl_sudent','tbl_grade.StudentID=tbl_sudent.SID')
->where('tbl_student.SID',$id)
->get()->result();
return $student;
}
I'm not totally certain you want to call get->row() on the first query, if that doesn't work try get->row_array()
I would like to flatten an object. This is what I've got so far:
{
"1": {
"id": 1,
"name": "parent",
"children": {
"4": {
"id": 4,
"name": "child1",
"parent": 1
},
"5": {
"id": 5,
"name": "child2",
"parent": 1
}
}
},
"2":{
"id": 2,
"name": "parent2"
}
}
And this is what I would like to accomplish. So keep the same order but flatten the object:
{
"1": {
"id": 1,
"name": "parent",
},
"4": {
"id": 4,
"name": "child1",
"parent": 1
},
"5": {
"id": 5,
"name": "child2",
"parent": 1
},
"2": {
"id": 2,
"name": "parent2"
}
}
So far I haven't found a solution to this. I've tried a function without much success:
protected function _flattenObject($array)
{
static $flattened = [];
if(is_object($array) && count($array) > 0)
{
foreach ($array as $key => $member) {
if(!is_object($member))
{
$flattened[$key] = $member;
} else
{
$this->_flattenObject($member);
}
}
}
return $flattened;
}
The tough part for me is to keep the same order (children below its parent). And the function mentioned above also removes all objects and almost only keeps the keys with its value, so it wasn't a great success at all.
Hopefully somebody over here knows a good solution for this.
By the way, the reason I want such flatten structure is because the system I have to work with, has trouble handling multidimensional arrays and objects. And I still want to display an hierarchy, which is possible with the flatten structure I described, because the objects actually contain a "level" key as well so I can give them some padding based on the "level" while still showing up below their parent.
EDIT:
The JSON didn't seem to be valid, so I modified it a bit.
The main problem seems to be that you are not doing anything with the returned results of your recursive function. Unless using static inside a method does some magic that I don't know of...
So this section:
if(!is_object($member))
{
$flattened[$key] = $member;
} else
{
// What happens with the returned value?
$this->_flattenObject($member);
}
Should probably be more like this:
if(!is_object($member))
{
$flattened[$key] = $member;
} else
{
// Add the returned array to the array you already have
$flattened += $this->_flattenObject($member);
}
Here is code that works. It adds a field "level" to your objects, to represent how many levels deep in the original hierarchy they were.
<?php
$obj = json_decode('[{
"id": 1,
"name": "parent",
"children": [{
"id": 4,
"name": "child1",
"parent": 1
}, {
"id": 5,
"name": "child2",
"parent": 1
}]
}, {
"id": 2,
"name": "parent2"
}]');
function _flattenRecursive($array, &$flattened, &$level)
{
foreach ($array as $key => $member) {
$insert = $member;
$children = null;
if (is_array($insert->children)) {
$children = $insert->children;
$insert->children = array();
}
$insert->level = $level;
$flattened[] = $insert;
if ($children !== null) {
$level++;
_flattenRecursive($children, $flattened, $level);
$level--;
}
}
}
function flattenObject($array)
{
$flattened = [];
$level = 0;
_flattenRecursive($array, $flattened, $level);
return $flattened;
}
$flat = flattenObject($obj);
var_dump($flat);
?>
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);
}