How to get the values only absent date and absent student id - php

Here i am doing one attendance module , that means who all are absent, i stored their id in database as json string ,here actually id 1 is absent on 2017-04-11 and 2017-04-12
id 2 is absent 2017-04-11 and 2017-04-13,upto now working fine, here after what i want to do means , i have one dynamic variable like loginId=2, i want to display the results like id 2 is which are the date he is absent, please see below my expected results.
student_absent_list (table name)
absendId studentAbsentId studentAbsentDate schoolId
1 ["1","2"] 2017-04-11 2
2 ["1"] 2017-04-12 2
3 ["2"] 2017-04-13 2
My Controller
public function getAbsentListStaff()
{
date_default_timezone_set('Asia/Kolkata');
$loginType = $_POST['loginType'];
if($loginType == 1)
{
$data = array(
"schoolId" => $_POST['schoolName'],
"classId" => $_POST['className'],
"sectionId" => $_POST['sectionName'],
"loginId" =>$_POST['loginId'],
);
$absentresponse= $this->Android_login_model->admin_options_listdisplayparent($data);
foreach ($absentresponse as $key => $value)
{
$absentresponse[$key]->studentAbsentId= json_decode($value->studentAbsentId,true);
}
if($absentresponse){
$return=array('status'=>"Success",'data'=>$absentresponse);
echo json_encode($return);
}
else{
$return=array('status'=>"Error",'description'=>"Data Not Found");
echo json_encode($return);
}
}
}
My Model
public function admin_options_listdisplayparent($params)
{
$this->db->select('*');
$this->db->where('status !=', '1');
$this->db->where('schoolId =',$params['schoolId']);
$this->db->where('classId =',$params['classId']);
$this->db->where('sectionId =',$params['sectionId']);
//$this->db->where('studentAbsentDate =',$params['absentDate']);
return $this->db->get('student_absent_list')->result();
}
My Expected Results
{
"status": "Success",
"data": [
{
"studentAbsentId": "2"
"studentAbsentDate": "2017-04-11",
"schoolId": "2",
"response":"absent"
},
{
"studentAbsentId": "2"
"studentAbsentDate": "2017-04-13",
"schoolId": "2",
"response":"absent"
}
]
}
Updated answer
{
"status": "Success",
"data": [
{
"absendId": "1",
"studentAbsentId": [
"1",
"2"
],
"studentAbsentDate": "2017-04-11",
"schoolId": "2",
"classId": "1",
"sectionId": "1",
"reg_date": "2017-04-13 01:01:03",
"created_by": "kanniyappan#g2evolution.co.in",
"status": "0"
},
{
"absendId": "2",
"studentAbsentId": [
"1"
],
"studentAbsentDate": "2017-04-12",
"schoolId": "2",
"classId": "1",
"sectionId": "1",
"reg_date": "2017-04-13 01:01:14",
"created_by": "kanniyappan#g2evolution.co.in",
"status": "0"
}
]
}

Try rewriting your model as below:
public function admin_options_listdisplayparent($params)
{
$condition = array(
'status !=' => '1',
'schoolId' => $params['schoolId'],
'classId' => $params['classId'],
'sectionId' => $params['sectionId']
);
$this->db->select('*');
$this->db->where($condition);
$this->db->like('studentAbsentId', '"' . $params['loginId'] . '"', 'both');
return $this->db->get('student_absent_list')->result();
}
Rewrite Controller as below:
public function getAbsentListStaff() {
date_default_timezone_set('Asia/Kolkata');
$loginType = $_POST['loginType'];
if($loginType == 1)
{
$data = array(
"schoolId" => $_POST['schoolName'],
"classId" => $_POST['className'],
"sectionId" => $_POST['sectionName'],
"loginId" =>$_POST['loginId'],
);
$absentresponse_data= $this->Android_login_model->admin_options_listdisplayparent($data);
$absentresponse = array();
foreach ($absentresponse_data as $res)
{
$row = array();
$row['studentAbsentId'] = $_POST['loginId'];
$row['studentAbsentDate'] = $res->studentAbsentDate;
$row['schoolId'] = $res->schoolId;
$row['response'] = 'absent';
$absentresponse[] = $row;
}
if(count($absentresponse) > 0){
$return = array('status'=>"Success",'data'=>$absentresponse);
echo json_encode($return);
} else {
$return = array('status'=>"Error",'description'=>"Data Not Found");
echo json_encode($return);
}
}
}

Related

List online users and get total "talep" count each user

I have a table for Talepler and Yonetim. Now Each talepler has his own users. and each user is mapped to that talepler by a field called user id. So how i can print out online users with total count in Talepler table by Count(*) with Join query.
Here my code with helper function. But i want with join.
$this->db->select('yonetim.id, yonetim.user, yonetim.onoff');
$this->db->from('yonetim');
$this->db->where('yonetim.onoff',1);
$query = $this->db->get();
$datam = array();
foreach ($query->result() as $data) {
$count = checkIfuserMax($data->id);
if($talepsay < 10 ) {
$datam[] = array(
'id' => $data->id,
'user' => $data->user,
'onoff' => $data->onoff,
'toplamtalep' => $count
);
}
}
echo json_encode($datam);
and here my helper function
function checkIfuserMax($id) {
$ci =& get_instance();
$ci->db->select('COUNT(*) as toplam');
$ci->db->where(array( 'hangiadmin' => $id, 'onaylayan' => null));
$ci->db->from('talepler');
$query = $ci->db->get();
$result = $query->result();
return $result[0]->toplam;
}
Finally here my json result
[
{
"id": "1",
"user": "user1",
"onoff": "1",
"toplamtalep": "13"
},
{
"id": "2",
"user": "user2",
"onoff": "1",
"toplamtalep": "0"
},
{
"id": "4",
"user": "user3",
"onoff": "1",
"toplamtalep": "2"
},
{
"id": "173",
"user": "user4",
"onoff": "1",
"toplamtalep": "6"
}
]
This code working properly. But i want to make this same result with "JOIN" query. Could you please help me about this query?

Php json_encode array and object array

I need to create a json with this format:
{
"reservs": [
{
"ResId": "58",
"time": "2020-05-15 19:41:50",
"boxEntering": null,
"boxClosing": null,
"active": "1",
"UserId": "29",
"BoxId": "4",
"boxPlace": null,
"box": {
"id": "4",
"Nom": "Hortillonages",
"Lat": "49.8953",
"Lng": "2.31034",
"place": "0",
"placeMax": "9"
}
}
]
}
in entries, a $header who check the user token(not use for my problem)
$table the table returned from PDO::FETCHASSOC from sql SELECT request
My php code:
function generateJson($table, headerChecker $header){
$final = array();
foreach ($table as $item) {
$box = array(
"id" => $item["id"],
"Nom" => $item["Nom"],
"Lat" => $item["Lat"],
"Lng" => $item["Lng"],
"place" => $item["place"],
"placeMax" => $item["placeMax"]
);
$reserv = array(
"ResId" => $item["ResId"],
"time" => $item["time"],
"boxEntering" => $item["boxEntering"],
"boxClosing" => $item["boxClosing"],
"active" => $item["active"],
"UserId" => $item["UserId"],
"BoxId" => $item["BoxId"],
"boxPlace" => $item["boxPlace"],
);
$reserv["box"] = $box;
array_merge($final,$reserv);
}
$arr = array("reservs" => $table);
$header->tokenJson($arr);
echo json_encode($arr);
}
I have this result
{"reservs": [
{
"ResId": "58",
"time": "2020-05-15 19:41:50",
"boxEntering": null,
"boxClosing": null,
"active": "1",
"UserId": "29",
"BoxId": "4",
"boxPlace": null,
"id": "4",
"Nom": "Hortillonages",
"Lat": "49.8953",
"Lng": "2.31034",
"place": "0",
"placeMax": "9",
"QRID": "",
"boxToken": ""
}]
}
I think the Json format eror is in the array_merge function.
What add array function can I use to not remove the Box object
Your problem is that you are not assigning the return of array_merge and using the wrong variable $table. Just dynamically append to $final:
foreach ($table as $item) {
// this all appears good
//
$reserv["box"] = $box;
$final[] = $reserv; // append to $final
}
$arr = array("reservs" => $final); // use $final
$header->tokenJson($arr);
echo json_encode($arr);
Merge the new $reserv into $final and assign it to $final, then use $final.
Try this one
function generateJson($table, headerChecker $header){
$final = array();
foreach ($table as $item) {
$box = array(
"id" => $item["id"],
"Nom" => $item["Nom"],
"Lat" => $item["Lat"],
"Lng" => $item["Lng"],
"place" => $item["place"],
"placeMax" => $item["placeMax"]
);
$reserv = array(
"ResId" => $item["ResId"],
"time" => $item["time"],
"boxEntering" => $item["boxEntering"],
"boxClosing" => $item["boxClosing"],
"active" => $item["active"],
"UserId" => $item["UserId"],
"BoxId" => $item["BoxId"],
"boxPlace" => $item["boxPlace"],
);
$reserv["box"] = $box;
$final[] = $reserv;
}
$arr = array("reservs" => $final);
$header->tokenJson($arr);
echo json_encode($arr);
}

how to remove specific key from multidimension array

This is what the result i need to come out with
"data": [
{
"ticket_category_id": "677",
"ticket_category_name": " Testing 500",
"ticket_category_order": "1",
"tickets":
[
{
"ticket_id": "927",
"ticket_title": "EDI Project Template with attachments",
"ticket_order": "1",
"due_date": "0000-00-00 00:00:00",
"created_date": "2018-05-16 10:01:04",
"edited_date": "2018-05-17 02:56:38",
"updated_date": "2018-05-17 02:56:38",
"is_complete": "0",
"total_comment": "0",
"total_attachment": "10",
"total_checklist_items": "48",
"total_completed_checklist_items": "0",
"label": [
{
"ticket_label_name": "",
"ticket_color_code": "#FF3B30"
},
"#D4891C": {
"ticket_label_name": "IN PROGRESS",
"ticket_color_code": "#D4891C"
}]
},
"people": []
},
{
"ticket_id": "928",
"ticket_title": "EDI Project Template",
"ticket_order": "2",
"due_date": "0000-00-00 00:00:00",
"created_date": "2018-05-16 10:01:04",
"edited_date": "0000-00-00 00:00:00",
"updated_date": "0000-00-00 00:00:00",
"is_complete": "0",
"total_comment": "0",
"total_attachment": "0",
"total_checklist_items": "48",
"total_completed_checklist_items": "0",
"label": [
{
"ticket_label_name": "",
"ticket_color_code": "#4CD964"
}]
},
"people": []
}
]
But what i get the result is like below
{
"data": [
{
"ticket_category_id": "677",
"ticket_category_name": " Testing 500",
"ticket_category_order": "1",
"tickets": {
"927": {
"ticket_id": "927",
"ticket_title": "EDI Project Template with attachments",
"ticket_order": "1",
"due_date": "0000-00-00 00:00:00",
"created_date": "2018-05-16 10:01:04",
"edited_date": "2018-05-17 02:56:38",
"updated_date": "2018-05-17 02:56:38",
"is_complete": "0",
"total_comment": "0",
"total_attachment": "10",
"total_checklist_items": "48",
"total_completed_checklist_items": "0",
"label": {
"#FF3B30": {
"ticket_label_name": "",
"ticket_color_code": "#FF3B30"
}
},
"people": []
}
}
},
{
"ticket_category_id": "677",
"ticket_category_name": " Testing 500",
"ticket_category_order": "1",
"tickets": {
"927": {
"ticket_id": "927",
"ticket_title": "EDI Project Template with attachments",
"ticket_order": "1",
"due_date": "0000-00-00 00:00:00",
"created_date": "2018-05-16 10:01:04",
"edited_date": "2018-05-17 02:56:38",
"updated_date": "2018-05-17 02:56:38",
"is_complete": "0",
"total_comment": "0",
"total_attachment": "10",
"total_checklist_items": "48",
"total_completed_checklist_items": "0",
"label": {
"#D4891C": {
"ticket_label_name": "IN PROGRESS",
"ticket_color_code": "#D4891C"
}
},
"people": []
}
}
},
And below is the code I have done, I using php mysql one to many relationship get all the data to be flat array, and then below code is convert single flat array into three multidimension array, but i meet a bottleneck. Please help to review my code to point out which part I need to change to become my expected result.
$result = array();
foreach($total_count as $Key => $Value){
$ticketCatId = $Value['ticket_category_id'];
$ticketId = $Value['ticket_id'];
$ticketColorCode = $Value['ticket_color_code'];
$ticketMember = $Value['user_id'];
$result[$ticketCatId]['ticket_category_id'] = $Value['ticket_category_id'];
$result[$ticketCatId]['ticket_category_name'] = $Value['ticket_category_name'];
$result[$ticketCatId]['ticket_category_order'] = $Value['ticket_category_order'];
if(!isset($result[$ticketCatId]['tickets'])) {
$result[$ticketCatId]['tickets'] = array();
}
// this code is append the ticket ID
if($ticketId && !isset($result[$ticketCatId]['tickets'][$ticketId])) {
$ticket = array(
'ticket_id' => $Value['ticket_id'],
'ticket_title' => $Value['ticket_title'],
'ticket_order' => $Value['ticket_order'],
'due_date' => $Value['due_date'],
'created_date' => $Value['created_date'],
'edited_date' => $Value['edited_date'],
'updated_date' => $Value['updated_date'],
'is_complete' => $Value['is_complete'],
'total_comment' => $Value['total_comment'],
'total_attachment' => $Value['total_attachment'],
'total_checklist_items' => $Value['total_checklist_items'],
'total_completed_checklist_items' => $Value['total_completed_checklist_items'],
'label' => array(),
'people' => array()
);
$result[$ticketCatId]['tickets'][$ticketId] = $ticket;
}
if($ticketColorCode && isset($result[$ticketCatId]['tickets'][$ticketId]) && !isset($result[$ticketCatId]['tickets'][$ticketId]['label'][$ticketColorCode])) {
$ticketColor = array(
'ticket_label_name' => $Value['ticket_label_name'],
'ticket_color_code' => $Value['ticket_color_code']
);
$result[$ticketCatId]['tickets'][$ticketId]['label'][$ticketColorCode] = $ticketColor;
}
if($ticketMember && isset($result[$ticketCatId]['tickets'][$ticketId]) && !isset($result[$ticketCatId]['tickets'][$ticketId]['people'][$ticketMember])) {
$ticketPeople = array(
'user_id' => $Value['user_id'],
'photo' => $Value['photo']
);
$result[$ticketCatId]['tickets'][$ticketId]['people'][$ticketMember] = $ticketPeople;
}
}
dd(json_encode(["data"=>$result]));
I don't have any sample data to work with, so I can't actually test this for you. The general idea though is that each time through the loop, you initialize a temporary array ($tmpArray = array();) and put all the loop-specific values into that array. Then, at the end of each loop iteration, you push that temporary array onto your $results array ($result[] = $tmpArray;), allowing PHP to automatically create sequential indexes for $results. The reason why you are getting nested JSON objects currently is because json_encode() will only produce JSON arrays from sequentially-index PHP arrays
$result = array();
foreach($total_count as $Key => $Value){
$ticketCatId = $Value['ticket_category_id'];
$ticketId = $Value['ticket_id'];
$ticketColorCode = $Value['ticket_color_code'];
$ticketMember = $Value['user_id'];
$tmpArray = array();
$tmpArray['ticket_category_id'] = $Value['ticket_category_id'];
$tmpArray['ticket_category_name'] = $Value['ticket_category_name'];
$tmpArray['ticket_category_order'] = $Value['ticket_category_order'];
if(!isset($tmpArray['tickets'])) {
$tmpArray['tickets'] = array();
}
// this code is append the ticket ID
if($ticketId && !isset($tmpArray['tickets'][$ticketId])) {
$ticket = array(
'ticket_id' => $Value['ticket_id'],
'ticket_title' => $Value['ticket_title'],
'ticket_order' => $Value['ticket_order'],
'due_date' => $Value['due_date'],
'created_date' => $Value['created_date'],
'edited_date' => $Value['edited_date'],
'updated_date' => $Value['updated_date'],
'is_complete' => $Value['is_complete'],
'total_comment' => $Value['total_comment'],
'total_attachment' => $Value['total_attachment'],
'total_checklist_items' => $Value['total_checklist_items'],
'total_completed_checklist_items' => $Value['total_completed_checklist_items'],
'label' => array(),
'people' => array()
);
$tmpArray['tickets'][$ticketId] = $ticket;
}
if($ticketColorCode && isset($tmpArray['tickets'][$ticketId]) && !isset($tmpArray['tickets'][$ticketId]['label'][$ticketColorCode])) {
$ticketColor = array(
'ticket_label_name' => $Value['ticket_label_name'],
'ticket_color_code' => $Value['ticket_color_code']
);
$tmpArray['tickets'][$ticketId]['label'][$ticketColorCode] = $ticketColor;
}
if($ticketMember && isset($tmpArray['tickets'][$ticketId]) && !isset($tmpArray['tickets'][$ticketId]['people'][$ticketMember])) {
$ticketPeople = array(
'user_id' => $Value['user_id'],
'photo' => $Value['photo']
);
$tmpArray['tickets'][$ticketId]['people'][$ticketMember] = $ticketPeople;
}
$result[] = $tmpArray;
}
dd(json_encode(["data"=>$result]));

PHP How to get a particular JSON values/parameter

This is my JSON Response came from an URL API. I use GuzzleHttp\Client and json_decode() inorder to manage.
[{
"INDEX_ID": "0",
"NOTES": "0; Farming"
},
{
"INDEX_ID": "1",
"NOTES": "Fruit Name; List of Fruits;"
},
{
"INDEX_ID": "2",
"NOTES": "Apple"
},
{
"INDEX_ID": "3",
"NOTES": "Orange"
},
{
"INDEX_ID": "4",
"NOTES": "Grapes"
},
{
"INDEX_ID": "5",
"NOTES": "Mango"
},
{
"INDEX_ID": "6",
"NOTES": "Animal Name; List of Animal;"
},
{
"INDEX_ID": "7",
"NOTES": "Pig"
},
{
"INDEX_ID": "8",
"NOTES": "Goat"
},
{
"INDEX_ID": "9",
"NOTES": "Cow"
}]
But I only need to save list of Fruits in my logfile. Can someone help me how to exclude the other json parameters and get only the particular json parameters using foreach loop or any method inorder to get that result.
I just want it to be like this:
[
{
"NOTE_NO." : "001",
"CATEGORY" : "FRUITS",
"LISTS_TO_BUY" : [
{
"FRUITS": "Apple"
},
{
"FRUITS": "Orange"
},
{
"FRUITS": "Grapes"
},
{
"FRUITS": "Mango"
}
]
}
]
He're my codes so far:
$response_body = json_decode($json_response, true);
$json_new_param = [];
foreach ($response_body as $value) {
$json_new_param[] = [
'FRUITS' => $value['NOTES']
];
}
$header = [
[
'NOTE_NO.' => '001',
'CATEGORY' => 'FRUITS',
'LISTS_TO_BUY' => $json_new_param
]
];
echo json_encode($header);
$json_response is the response given above.
You might use array_reduce to return an array where the key will be the first word from the value using implode which has this structure: "NOTES": "Fruit Name; List of Fruits;". The key for this would then be "Fruits".
During the array_reduce keep track of the current key using a variable $currKey
At the end you could then get the data by using "FRUIT" (Which is the first word) as the array key: $response_body["FRUIT"]
$response_body = json_decode($json_response, true);
$currKey = "0";
$response_body = array_reduce($response_body, function ($carry, $item) use (&$currKey){
if (strpos($item['NOTES'], 'Name; List') !== false) {
$currKey = strtoupper(explode(" ", $item["NOTES"], 2)[0]);
return $carry;
}
$carry[$currKey][] = ["FRUITS" => $item["NOTES"]];
return $carry;
});
$result = [
[
"NOTE_NO" => "001",
"CATEGORY" => ($name = "FRUITS"),
"LISTS_TO_BUY" => $response_body["FRUIT"]
]
];
echo json_encode($result, JSON_PRETTY_PRINT);
That will result in:
[
{
"NOTE_NO": "001",
"CATEGORY": "FRUITS",
"LISTS_TO_BUY": [
{
"FRUITS": "Apple"
},
{
"FRUITS": "Orange"
},
{
"FRUITS": "Grapes"
},
{
"FRUITS": "Mango"
}
]
}
]
Demo
Try this code .
$json_new_param = [];
$fruitFlag = false;
foreach ($response_body as $value) {
if(strpos($value['NOTES'],'Fruit Name') !== false){
$fruitFlag = true;
continue;
}
if(strpos($value['NOTES'],'Animal Name') !== false){
$fruitFlag = false;
}
if($fruitFlag == true){
$json_new_param[] = [
'FRUITS' => $value['NOTES']
];
}
}
echo json_encode($json_new_param, JSON_PRETTY_PRINT);

Creating nested JSON using PHP MySQL

I have an SQL Query returning certain fields, I am using json_encode() to get the data in JSON format, however I am having trouble getting it in the format I want.
PHP Code
<?php
function data() {
$runDistanceBasedOnCityQuery = "SELECT rc.id, rc.cityId, c.cityName, rc.runId, r.distance, rc.status FROM run_city rc INNER JOIN cities c ON c.id = rc.cityId INNER JOIN run_distance r ON r.id = rc.runId ORDER BY c.cityName";
$runDistanceBasedOnCityResult = $db->prepare($runDistanceBasedOnCityQuery);
$runDistanceBasedOnCityResult->bindParam(":cityId", $cityId, PDO::PARAM_INT);
$runDistanceBasedOnCityResult->execute();
$runDistanceBasedOnCityOutput = $runDistanceBasedOnCityResult->rowCount();
if ($runDistanceBasedOnCityOutput > 0) {
while ($runDistanceBasedOnCityRow = $runDistanceBasedOnCityResult->fetch(PDO::FETCH_ASSOC)) {
$array1 = array($runDistanceBasedOnCityRow['runId'], $runDistanceBasedOnCityRow['distance'], $runDistanceBasedOnCityRow['status']);
for ($i = 0; $i < sizeof($array1); $i++) {
$array2 = array("id" => $runDistanceBasedOnCityRow['id'], "runId" => $runDistanceBasedOnCityRow['cityId'], $runDistanceBasedOnCityRow['cityName'] => $array1);
}
$finalResultRunDistanceBasedOnCity[] = $array2;
}
$responseRunDistanceBasedOnCity = $finalResultRunDistanceBasedOnCity;
} else {
$responseRunDistanceBasedOnCity = 'Runs not found';
}
$result = array("status" => true,
"runsBasedOnCity" => $responseRunDistanceBasedOnCity
);
json($result);
}
function json($data) {
header('Content-Type:application/json');
if (is_array($data)) {
echo json_encode($data);
}
}
?>
The JSON format I am getting
"runsBasedOnCity": [
{
"id": "1",
"runId": "1",
"Bengaluru": [
"2",
"10k",
"1"
]
},
{
"id": "2",
"runId": "1",
"Bengaluru": [
"1",
"5k",
"1"
]
},
{
"id": "3",
"runId": "1",
"Bengaluru": [
"5",
"3k",
"0"
]
},
{
"id": "4",
"runId": "2",
"Chennai": [
"1",
"5k",
"1"
]
},
{
"id": "5",
"runId": "2",
"Chennai": [
"2",
"10k",
"1"
]
},
{
"id": "6",
"runId": "2",
"Chennai": [
"4",
"15k",
"1"
]
}
]
The Format I Require
"runsBasedOnCity": [
{
"id": "1",
"cityId": "1",
"Bengaluru":
[
{
runId : "2",
distance : "10k",
status : "1"
},
{
runId : "1",
distance: "5k",
status : "1"
},
{
runId : "5",
distance : "3k",
status : "0"
}
]
},
{
"id": "2",
"cityId": "2",
"Chennai":
[
{
runId : "1",
distance : "5k",
status : "1"
},
{
runId : "2",
distance: "10k",
status : "1"
},
{
runId : "4",
distance : "15k",
status : "1"
}
]
}
I am not able to figure out a better way of doing this, I am fairly new to this, do help me out. Thanks !
To efficiently group the subarray data, you should implement temporary keys. cityId is a suitable value to group by -- because cityNames may intentionally duplicate in the future but cityId must never un/intentionally duplicate in your database table.
When each new cityId is encountered, the conditional isset() call will determine whether a new/full set of data should be stored, or if data should merely be appended to the subarray.
I am calling array_slice() since it cuts down on unnecessary syntax / code-bloat.
After iterating through all of the rows, you can reindex the $result array, nest it inside runBasedOnCity, and add the status element.
I'll show my demo with PRETTY_PRINT so that it is easier to read, but in your actual code, you should remove the parameter. Also, a word of advice -- try to keep your variable names brief for improved readability.
Code: (Demo)
$resultset = [
["id" => "1", "cityId" => "1", "cityName" => "Bengaluru", "runId" => "2", "distance" => "10k", "status" => "1"],
["id" => "2", "cityId" => "1", "cityName" => "Bengaluru", "runId" => "1", "distance" => "5k", "status" => "1"],
["id" => "3", "cityId" => "1", "cityName" => "Bengaluru", "runId" => "5", "distance" => "3k", "status" => "0"],
["id" => "4", "cityId" => "2", "cityName" => "Chennai", "runId" => "1", "distance" => "5k", "status" => "1"],
["id" => "5", "cityId" => "2", "cityName" => "Chennai", "runId" => "2", "distance" => "10k", "status" => "1"],
["id" => "6", "cityId" => "2", "cityName" => "Chennai", "runId" => "4", "distance" => "15k", "status" => "1"]
];
foreach ($resultset as $row) {
if (!isset($result[$row["cityId"]])) {
$result[$row["cityId"]] = array("id" => $row["id"], "cityId" => $row["cityId"], $row["cityName"] => array(array_slice($row,-3)));
} else {
$result[$row['cityId']][$row["cityName"]][] = array_slice($row,-3);
}
}
if (!isset($result)) { // don't need to check rowCount() at all
$result = 'Runs not found';
} else {
$result = array_values($result);
}
$result = array("status" => true, "runsBasedOnCity" => $result);
var_export(json_encode($result, JSON_PRETTY_PRINT));
Output:
'{
"status": true,
"runsBasedOnCity": [
{
"id": "1",
"cityId": "1",
"Bengaluru": [
{
"runId": "2",
"distance": "10k",
"status": "1"
},
{
"runId": "1",
"distance": "5k",
"status": "1"
},
{
"runId": "5",
"distance": "3k",
"status": "0"
}
]
},
{
"id": "4",
"cityId": "2",
"Chennai": [
{
"runId": "1",
"distance": "5k",
"status": "1"
},
{
"runId": "2",
"distance": "10k",
"status": "1"
},
{
"runId": "4",
"distance": "15k",
"status": "1"
}
]
}
]
}'
After explaining how you wanted to preserve the id values in the subarrays, here is that solution:
Code: (Demo)
foreach ($resultset as $row) {
if (!isset($result[$row["cityId"]])) {
$result[$row["cityId"]] = array("cityId" => $row["cityId"], $row["cityName"] => array(array("id" => $row["id"])+array_slice($row,-3)));
} else {
$result[$row['cityId']][$row["cityName"]][] = array("id" => $row["id"])+array_slice($row,-3);
}
}
if (!isset($result)) { // don't need to check rowCount() at all
$result = 'Runs not found';
} else {
$result = array_values($result);
}
$result = array("status" => true, "runsBasedOnCity" => $result);
var_export(json_encode($result, JSON_PRETTY_PRINT));

Categories