How to get JSON data from database groupby Date in Codeigniter - php

I have a table and I want to get data from database and return it in JSON fromat date vise, below is my table:
id userId Date Time record
1 1 15-Oct-2017 3:50 152
2 1 15-Oct-2017 4:30 142
3 1 16-Oct-2017 8:50 130
4 2 15-Oct-2017 2:00 90
5 2 15-Oct-2017 4:50 154
6 2 15-Oct-2017 5:00 120
I created a function in which I called the data from database and return the output in JSON fromat
public function getRecord()
{
$userId = $this->input->get('userId');
$this->db->from('xyz');
$this->db->where('userId',$userId);
$record = $this->db->get()->result();
return $this->output->set_output(json_encode(array(
'status' => 'Ok',
'statusCode' =>'801',
'response' => $record
)));
}
it returns me something like this, which is not required by me (I know I didn't do it in right way)
{
"status": "Ok",
"statusCode": "801",
"response": Array[3][
{
"id": "1",
"userId": "1",
"date": "15-Oct-2017",
"time": "3:50",
"record": "152"
},
{
"id": "2",
"userId": "1",
"date": "15-Oct-2017",
"time": "4:30",
"record": "142"
},
{
"id": "3",
"userId": "1",
"date": "16-Oct-2017",
"time": "8:50",
"record": "130"
}
]
}
But I want some thing like this, the output will be putted in date vise
{
"status": "Ok",
"statusCode": "801",
"response": Array[3][
[
"date": "15-Oct-2017"
{
"id": "1",
"userId": "1",
"date": "15-Oct-2017",
"time": "3:50",
"record": "152"
},
{
"id": "2",
"userId": "1",
"date": "15-Oct-2017",
"time": "4:30",
"record": "142"
}
],
[
"date": "16-Oct-2017"
{
"id": "3",
"userId": "1",
"date": "16-Oct-2017",
"time": "8:50",
"record": "130"
}
]
]
}

Although the result json that you presented seems to no be valid, and since, I think you want the records grouped by date, try looping through the records array grouping them on another array by the date:
<?php
public function getRecord()
{
$userId = $this->input->get('userId');
$this->db->from('xyz');
$this->db->where('userId',$userId);
$record = $this->db->get()->result();
$orderedRecord = [];
foreach ($record as $r) {
if (!isset($orderedRecord[$r->Date])) {
$orderedRecord[$r->Date] = [];
}
$orderedRecord[$r->Date][] = $r;
}
return $this->output->set_output(json_encode(array(
'status' => 'Ok',
'statusCode' =>'801',
'response' => $orderedRecord
)));
}
?>

Related

how should i decode the correct json response?

I am using Laravel 5.7 to build an API that provides a JSON response. I am creating the following JSON but it needs some changes. Table contain booking_pics columns in which multiple images stored using , separated. I want fetch in json as object in array. i am display json but only last image is display others is not, need solution.
Controller:
$get_booking_details= DB::table('table_booking_list')
->join('table_booking_details', 'table_booking_list.booking_id', '=', 'table_booking_details.booking_id')
->select('table_booking_details.*')
->where('table_booking_details.booking_id',$booking_id)
->get();
foreach($get_booking_details as $item)
{
foreach(explode(",",$item->booking_pics) as $items)
{
$item->booking_pics=[["image" => $items]];
}
}
return response()->json(['success' => '1','data' =>$get_booking_details]);
json response:
{
"success": "1",
"data": [
{
"id": 1,
"booking_list_id": 1,
"booking_id": 1,
"booking_name": "hockey stadium",
"booking_area": "kolhapur",
"booking_status": 0,
"time": "6.00 am to 8.00pm",
"booking_pics": [
{
"image": "http://192.168.1.132:8000/images/ground_pic/2.jpg"
}
],
"available_sports": "hockey,cricket",
"booking_amenities": "parking,toilet,water",
"booking_rating": 4.5,
"booking_area_address": "MSEB Ring Road, Datta Colony, Kolhapur, Maharashtra, 416008",
"longitude": "85.501980",
"latitude": "23.624420",
"updated_at": "2019-06-26 16:42:02",
"created_at": "0000-00-00 00:00:00"
}
]
}
Required json:
{
"success": "1",
"data": [{
"id": 1,
"booking_list_id": 1,
"booking_id": 1,
"booking_name": "hockey stadium",
"booking_area": "kolhapur",
"booking_status": 0,
"time": "6.00 am to 8.00pm",
"booking_pics": [{
"image": "http://192.168.1.132:8000/images/ground_pic/1.jpg"
},
{
"image": "http://192.168.1.132:8000/images/ground_pic/2.jpg"
}
],
"available_sports": "hockey,cricket",
"booking_amenities": "parking,toilet,water",
"booking_rating": 4.5,
"booking_area_address": "MSEB Ring Road, Datta Colony, Kolhapur, Maharashtra, 416008",
"longitude": "85.501980",
"latitude": "23.624420",
"updated_at": "2019-06-26 16:42:02",
"created_at": "0000-00-00 00:00:00"
}]
}
Do it this way
foreach($get_booking_details as $item)
{
foreach(explode(",",$item->booking_pics) as $items)
{
$item->booking_pics["image"][] = $items;
}
}
fastest way would be creating a model and casting the data from database as a json
in model
protected $casts = [
'booking_pics' => 'json',
];

Filter array elements based on value of a key element for Given IDs

I have a JSON object in PHP Like
$my_json = '[{
"No": "1",
"Id": "10",
"msg": "Value is 10"
},
{
"No": "2",
"Id": "55",
"msg": "value is 55"
}, {
"No": "3",
"Id": "38",
"msg": "value is 38 "
}, {
"No": "4",
"Id": "95",
"msg": "value is 95 "
} ]';
I have converted it to PHP object array using $obj_arr= json_decode($my_json);
Now, based on user selection I want to filter array element
Eg. if the user selects "ID" as 38 and 55 then new array should note have ID 10 and 95 IN it and must contain all other data related to those ID just like an original one
EG
$final_json = '[
{
"No": "2",
"Id": "55",
"msg": "value is 55"
}, {
"No": "3",
"Id": "38",
"msg": "value is 38 "
} ]';
Try this:
<?php
$my_json = '[{
"No": "1",
"Id": "10",
"msg": "Value is 10"
},
{
"No": "2",
"Id": "55",
"msg": "value is 55"
}, {
"No": "3",
"Id": "38",
"msg": "value is 38 "
}, {
"No": "4",
"Id": "95",
"msg": "value is 95 "
} ]';
$selected = [38, 55];
$obj = json_decode($my_json);
$result = array_filter($obj, function($row) use ($selected) {
return in_array($row->Id, $selected);
});
echo json_encode(array_values($result), JSON_PRETTY_PRINT);
Output:
[
{
"No": "2",
"Id": "55",
"msg": "value is 55"
},
{
"No": "3",
"Id": "38",
"msg": "value is 38 "
}
]
If you want to filter out the selected values above instead of keep them, return the negation of in_array.

Delete object from json file with PHP

Well, I have a web project and I have to be saving things temporarily, I started work with a json file, so far I can add and update.
The json file looks like this:
[
{
"username": "Baldwin",
"products": [
{
"id": 0,
"amount": 10
},
{
"id": 1,
"amount": 9
},
{
"id": 2,
"amount": 9
}
]
},
{
"username": "Alice",
"products": [
{
"id": 0,
"amount": 11
},
{
"id": 1,
"amount": 13
},
{
"id": 2,
"amount": 6
}
]
},
{
"username": "Terry",
"products": [
{
"id": 0,
"amount": 12
},
{
"id": 1,
"amount": 14
},
{
"id": 2,
"amount": 5
}
]
}
]
The problem comes when I want to delete an specific array or when I want to delete it completely, I can do it and it works fine, but I have the doubt about why when I delete the object, other fields are add to the json file, like an id.
When i delete just one product inside of the "products" array something like this happen:
[
{
"username": "Baldwin",
"products": { "1": { "id": 1, "amount": 9 }, "2": { "id": 2, "amount": 9 } }
},
{
"username": "Alice",
"products": [
{ "id": 0, "amount": 11 },
{ "id": 1, "amount": 13 },
{ "id": 2, "amount": 6 }
]
},
{
"username": "Terry",
"products": [
{ "id": 0, "amount": 12 },
{ "id": 1, "amount": 14 },
{ "id": 2, "amount": 5 }
]
}
]
And when i delete a complete array from the json file, something like this happen:
{
"1": {
"username": "Alice",
"products": [
{ "id": 0, "amount": 11 },
{ "id": 1, "amount": 13 },
{ "id": 2, "amount": 6 }
]
},
"2": {
"username": "Terry",
"products": [
{ "id": 0, "amount": 12 },
{ "id": 1, "amount": 14 },
{ "id": 2, "amount": 5 }
]
}
}
My php file to delete:
<?php
// load file
$data = file_get_contents('results.json');
// decode json to associative array
$json_arr = json_decode($data, true);
$flag = false;
// We check if the user wants to delete all or just one product
if(isset($_POST["all"])):
$username = $_POST["username"];
foreach ($json_arr as $key => $value):
// find the username on the json file
if($value["username"] == $username):
unset($json_arr[$key]);
break;
endif;
endforeach;
elseif(isset($_POST["one"])):
$username = $_POST["username"];
$id = $_POST["id"];
foreach ($json_arr as $key => $value):
// find the username on the json file
if($value["username"] == $username):
// loop products of the current username
foreach ($json_arr[$key]["products"] as $k => $product):
// find the id of the product
if($json_arr[$key]["products"][$k]["id"] == (int)$id):
// delete the product
unset($json_arr[$key]["products"][$k]);
endif;
endforeach;
endif;
endforeach;
endif;
// encode json and save to file
file_put_contents('results.json', json_encode($json_arr));
// redirect to show.php
header("Location: show.php");
?>
I've been taking a look to questions like this one but i couldn't find something with php, i would like to know how to solve this or if this is normal.
What happens when you use unset($json_arr[0]) is that the first element is removed, but the keys are not updated. If you inspect the array after the removal, you'll find that your array has two elements, at $json_arr[1] and $json_arr[2].
When you then perform a json_encode($json_arr) on this, PHP's JSON decoder looks at the array and since arrays are supposed to begin at the 0th element but this array begins at 1, it decides that in order to preserve the keys, the array would have to be converted to an associative array - which transforms the integer array keys into string keys in JSON.
For a short and quick solution, you can try:
$json_arr = array_diff($json_arr, [$key]);
You could even use array_splice or array_values - see here for inspiration.

Yii 2 Active Record nested many to many relations

I have 4 table products, properties, property_items, property_product with relations like this
Product has many properties.
Property has many property_items.
Product has many property_items.
Property_product is intermediary table.
-- products --
Id name
1 Arrabiata
2 Bolognese
--properties --
Id name
1 Pasta type
2 Size
-- property_items --
Id name value property_id
1 Spinach spaghetti ..... 1
2 Linguine ..... 1
3 Spaghetti ..... 1
4 Small .... 2
5 Medium .... 2
6 Large ... 2
-- property_product --
product_id property_id property_item_id
1 1 1
1 1 2
1 2 4
1 2 6
2 1 2
2 1 3
2 2 5
I try use Gii to create those models with relations .
class Products extends \yii\db\ActiveRecord
{
//code
....
public function getProperties()
{
return $this->hasMany(Properties::className(), ['id' => 'property_id'])
->viaTable('property_product', ['product_id' => 'id']);
}
}
class Properties extends \yii\db\ActiveRecord
{
//code
...
public function getPropertyItems()
{
return $this->hasMany(PropertyItems::className(), ['property_id' => 'id']);
}
}
I want to query data with multi nested relation.
How can i create json response with below format in one active record query ?
[
{
"id": "1",
"name": "Arrabiata",
"properties": [
{
"id": "1",
"name": "Pasta type",
"property_items" : [
{
"id": "1",
"name": "Spinach spaghetti",
},
{
"id": "2",
"name": "Linguine",
},
]
},
{
"id": "2",
"name": "Size",
"property_items" : [
{
"id": "4",
"name": "Small",
},
{
"id": "6",
"name": "Large",
},
]
},
],
},
{
"id": "2",
"name": "Bolognese",
"properties": [
{
"id": "1",
"name": "Pasta type",
"property_items" : [
{
"id": "2",
"name": "Linguine",
},
{
"id": "3",
"name": "Spaghetti",
},
]
},
{
"id": "2",
"name": "Size",
"property_items" : [
{
"id": "5",
"name": "Medium",
},
]
},
]
}]
I use this query but it took too much perfomance
Menus::find()->with(['products' => function ($query) {
$query->with(['properties']);
}])
->where(['>', 'status', 0])
->andWhere(['resid' => $id])->asArray()->all();;
foreach ($menus as &$menu) {
foreach ($menu['products'] as &$product) {
foreach ($product['properties'] as &$property) {
$propertyItems = PropertyItems::find()->where(['property_id' => $property['id']]
)
->leftJoin('property_product', 'property_items.id = property_product.property_item_id')
->where(['property_product.product_id' => $product['id'],
'property_product.property_id' => $property['id']])
->asArray()->all();
$property['propertyItems'] = $propertyItems;
}
}
}
If I use this query
Menus::find()->with(['products' => function ($query) {
$query->with(['properties' => function ($query) {
$query->with(['propertyItems']);
}
]);
}
])->asArray()->all();
But the result not same as i expected because all property_items will show up in properties instead of depend on relating with products via table "property_product"
[
{
"id": "1",
"name": "Arrabiata",
"properties": [
{
"id": "1",
"name": "Pasta type",
"property_items" : [
{
"id": "1",
"name": "Spinach spaghetti",
},
{
"id": "2",
"name": "Linguine",
},
{
"id": "3",
"name": "Spaghetti",
},
]
},
{
"id": "2",
"name": "Size",
"property_items" : [
{
"id": "4",
"name": "Small",
},
{
"id": "6",
"name": "Large",
},
{
"id": "5",
"name": "Medium",
},
]
},
],
},
{
"id": "2",
"name": "Bolognese",
"properties": [
{
"id": "1",
"name": "Pasta type",
"property_items" : [
{
"id": "1",
"name": "Spinach spaghetti",
},
{
"id": "2",
"name": "Linguine",
},
{
"id": "3",
"name": "Spaghetti",
},
]
},
{
"id": "2",
"name": "Size",
"property_items" : [
{
"id": "4",
"name": "Small",
},
{
"id": "6",
"name": "Large",
},
{
"id": "5",
"name": "Medium",
},
]
}
]
}]
Thanks in advance.
You have to override the function fields() of the Products and Properties models.
for example:
class Products extends ActiveRecord {
function fields(){
return ['properties'];
}
}
class Properties extends ActiveRecord {
function fields(){
return ['property_items'];
}
}

Structure JSON output with PHP

I am trying to generate a JSON output from the DATABASE with MySQL.
The result that I want is that I want an array around two matching ID's found in the tabel in the database.
To visualise what I wish to achieve here is my code:
This is my query
$sql = "SELECT * FROM `flower_garden` WHERE `id_flower` IN (0, 1)";
$result = mysql_query($sql);
while($record = mysql_fetch_assoc($result)) {
$rows[] = $record;
}
print json_encode($rows);
This is the JSON result I wish to achieve:
(What I want)
[
[
"id": "1",
"id_flower": "3",
"Title": "rose",
"Price": 1.25,
"Number": 15
},
{
"id": "2",
"id_flower": "3",
"Title": "daisy",
"Price": 0.75,
"Number": 25
}
],
[
{
"id": "3",
"id_flower": "6",
"Title": "rose",
"Price": 1.25,
"Number": 15
},
{
"id": "4",
"id_flower": "6",
"Title": "daisy",
"Price": 0.75,
"Number": 25
}
]
]
Visual result:
So, I want the matching ID's (in this case id_flower) put in one array.
This is the result I get:
(What I get)
[
[
"id": "1",
"id_flower": "3",
"Title": "rose",
"Price": 1.25,
"Number": 15
},
{
"id": "2",
"id_flower": "3",
"Title": "daisy",
"Price": 0.75,
"Number": 25
},
{
"id": "3",
"id_flower": "6",
"Title": "rose",
"Price": 1.25,
"Number": 15
},
{
"id": "4",
"id_flower": "6",
"Title": "daisy",
"Price": 0.75,
"Number": 25
}
]
]
Visual result:
Try this
foreach ($rows as $key => $val) {
$return[$val['id_flower']][] = $val;
}
echo json_encode($return);
Please note I have not tested it.
$sql = "SELECT * FROM `flower_garden` WHERE `id_flower` IN (0, 1)";
$result = mysql_query($sql);
$rows = array();
while($record = mysql_fetch_assoc($result)) {
array_push($rows[$record["id_flower"]], $record);
}
$result = array();
foreach($rows as $k => $v){
array_push($result, $v);
}
echo json_encode($result);
test yourself !

Categories