Hello i am building a REST API using Codeigniter. The thing is that i want to get the prices for a specific property. I get the prices correctly but i want to get the prices for the current year only. The table has prices from 2003-2017 so i only want to display prices greater or equal than the current year.
So i have something like this:
{
"status": "success",
"status_code": "200",
"message": "200 OK",
"response": [
{
"property_id": "3",
"price_id": "66",
"price": "350",
"currency": "EUR",
"timeframe_id": "1"
},
{
"property_id": "3",
"price_id": "70",
"price": "300",
"currency": "EUR",
"timeframe_id": "6"
}
and at the very bottom:
{
"property_id": "3",
"price_id": "167547",
"price": "500",
"currency": "EUR",
"timeframe_id": "1186",
"periods": [
{
"from": "2015-12-12",
"to": "2015-12-19",
"day": "Sa"
}
]
},
{
"property_id": "3",
"price_id": "167548",
"price": "550",
"currency": "EUR",
"timeframe_id": "1187",
"periods": [
{
"from": "2015-12-19",
"to": "2015-12-26",
"day": "Sa"
}
]
}
]
}
What i want to do is only display the prices that they have periods. So i used unset but the results come in a weird way like this:
{
"status": "success",
"status_code": "200",
"message": "200 OK",
"response": {
"582": {
"property_id": "3",
"price_id": "167498",
"price": "300",
"currency": "EUR",
"timeframe_id": "1137",
"periods": [
{
"from": "2015-01-03",
"to": "2015-01-10",
"day": "Sa"
}
]
},
"583": {
"property_id": "3",
"price_id": "167499",
"price": "300",
"currency": "EUR",
"timeframe_id": "1138",
"periods": [
{
"from": "2015-01-10",
"to": "2015-01-17",
"day": "Sa"
}
]
}
How can i remove this 582:{ in front of every object? My code is:
$prices = $this->Model_prices->get_many_by(array('Objekt' => $property_id));
foreach ($prices as $key => $value) {
$data = $this->timeframe_get($value['timeframe_id']);
foreach ($data as $k => $v) {
$from = $v['from'];
if ( date("Y", strtotime(".$from.")) >= "2015" ) {
$prices[$key]['periods'] = $data;
}else{
unset($prices[$key]);
}
}
}
$this->response(array('status' => 'success', 'status_code' => '200', 'message' => '200 OK', 'response' => $prices));
The timeframe_get method:
public function timeframe_get($timeframe_id){
$this->load->model('Model_timeframe');
$this->load->database();
// $sql = "SELECT ID as id, von as _from, bis as _to FROM zeitraeumevk WHERE ID = $timeframe_id AND YEAR(von) >= YEAR('2015-01-01')";
// $query = $this->db->query($sql);
$timeframes = $this->Model_timeframe->get_many_by(array('ID' => $timeframe_id));
if ($timeframes) {
return $timeframes;
} else {
return "There is no timeframe specified for this property";
}
}
Any ideas? Thank you in advance!!!
You can use the "Query Builder Class" to build the query and retrieve the data in the form that you want, something like:
$this->db->where(array('Objekt' => $property_id, 'from >='=>'2015-01-01'))->get('prices');
I have finally managed to solve it like this:
$sql = "SELECT z.ID as id, z.von as _from, z.bis as _to, p.ID as price_id, p.Objekt as property_id, p.Preis as price FROM timeframe` z INNER JOIN prices p ON z.ID = p.Zeitraum INNER JOIN properties o ON p.Objekt = o.ID WHERE p.Objekt = ".$property_id." AND YEAR(z.von) >= YEAR('2015-01-01');";
But it would have been nicer to actually can use the built in method that MY_Model uses.
Related
I need to create this json in the following format
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "Product 1",
"quantity": "1",
"price": "5.00"
},
{
"productName": "Product 2",
"quantity": "2",
"price": "24.00"
},
{
"productName": "Product 3",
"quantity": "1",
"price": "6.50"
}
]
},
{
"orderId": "2",
"orderDate": "2/06/2021",
"products": [
{
"productName": "Product 1",
"quantity": "1",
"price": "3.00"
},
{
"productName": "Product 2",
"quantity": "1",
"price": "11.50"
}
]
},
{
"orderId": "3",
"orderDate": "03/05/2021",
"products": [
{
"productName": "Product 1",
"quantity": "1",
"price": "3.00"
},
{
"productName": "Product 2",
"quantity": "1",
"price": "11.50"
}
]
}
]
}
This is my code that I use to retrive the information from the database
$stmt = $con->prepare("SELECT OrderID, OrderDate, ProductName, ProductQty, ProductPrice FROM Orders where CustomerID = ?");
$stmt->bind_param("s", $CustomerID);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($OrderID, $OrderDate, $ProductName, $ProductQty, $ProductPrice);
while($stmt->fetch()) {
$message[] = array(
"status" => true,
"message" => "",
"orders" => array(
array(
"orderId" => "$OrderID",
"orderDate" => "$OrderDate",
"products" => array(
array(
"productName" => "$ProductName",
"quantity" => "$ProductQty",
"price" => "$ProductPrice"
),
)
)
)
);
}
$json = $message;
header('content-type: application/json');
echo json_encode($json);
This is how the information from the database displays. I do not know how to show the information about the products correctly. Can anyone show me how to do it in the format that I require in php? Thanks in advance for any help.
[
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "620",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "240",
"quantity": "1",
"price": "5.00"
},
{
"productName": "270",
"quantity": "1",
"price": "10.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "30",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "280",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "610",
"quantity": "1",
"price": "5.00"
}
]
}
]
}
]
You are repeating the orders structure which you shouldn't. That's why you get the wrong structure. This is what you should do instead (your code, modified):
// specify your return response array only once
$message = array(
"status" => true,
"message" => "",
"orders" => array();
);
$stmt = $con->prepare("SELECT OrderID, OrderDate, ProductName, ProductQty, ProductPrice FROM Orders where CustomerID = ?");
$stmt->bind_param("s", $CustomerID);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($OrderID, $OrderDate, $ProductName, $ProductQty, $ProductPrice);
while($stmt->fetch()) {
// and fill its "orders" member with your orders list
$message["orders"][] = array(
"orderId" => "$OrderID",
"orderDate" => "$OrderDate",
"products" => array(
array(
"productName" => "$ProductName",
"quantity" => "$ProductQty",
"price" => "$ProductPrice"
),
)
);
}
$json = $message;
header('content-type: application/json');
echo json_encode($json);
You can try like below
const data = [
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "620",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "240",
"quantity": "1",
"price": "5.00"
},
{
"productName": "270",
"quantity": "1",
"price": "10.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "30",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "280",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "610",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": false,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "800",
"quantity": "50",
"price": "5.00"
}
]
}
]
},
{
"status": false,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "1800",
"quantity": "50",
"price": "5.00"
}
]
}
]
}
];
const resutl = data.reduce((acc, cur) => {
const key = cur.status ? "successItems" : "failureItems";
if (acc[key]) {
return {
...acc,
[key]: {
status: cur.status,
messgae: '',
orders: [
...acc[key].orders,
...cur.orders
]
}
}
} else {
return {
...acc,
[key]: {
status: cur.status,
messgae: '',
orders: [
...cur.orders
]
}
}
}
}, {});
console.log('resutl', resutl);
console.log('resutl', Object.values(resutl));
i need to display records from my database mysql grouped by date to JSON in PHP.
i have table :
--- transaction ---
- id
- date (Y-m-d H:i:s)
- user
- price
- product_id
- quantity
-------------------
And i wish display to JSON like this
{
"status": {
"code": 200,
"message": "Success"
},
"data": [
{
"date": "1 June 2020",
"detail": [
{
"id": 1,
"date_trx": "01-06-2020 15:22:54",
"user": "User A",
"price": 500,
"product_id": "Product A",
"quantity": 2
},
{
"id": 1,
"date_trx": "01-06-2020 17:22:54",
"user": "User B",
"price": 500,
"product_id": "Product H",
"quantity": 2
}
]
},
{
"date": "2 June 2020",
"detail": [
{
"id": 1,
"date_trx": "02-06-2020 15:22:54",
"user": "User A",
"price": 500,
"product_id": "Product A",
"quantity": 2
}
]
}
]
}
i have to tried some code from google or stackoverflow, but not like my wish
** EDIT **
this is my code have tried
$search = $call->query("SELECT * FROM transaction WHERE ORDER BY date DESC");
if($search->num_rows > 0){
$date = null;
$array = [];
while($record = $search->fetch_assoc()) {
$currentDate = date('Y-m-d', strtotime($record['tgl']));
if ($currentDate != $date) {
// echo "<h1>$currentDate</h1>";
$tgl = $currentDate;
}
$date = $currentDate;
// echo $record['rid']."<br>";
if(is_array($array) && $array['date'] != $tgl){
$arr = array(
'date' => $tgl,
'detail' => array(
'id' => $record['rid'],
'date_trx' => $record['tgl'],
'user' => $record['user'],
'price' => $record['price'],
'product_id' => $record['product'],
'quantity' => $record['quantity']
)
);
array_push($array, $arr);
}
}
$output = ['result' => true, 'data' => $array];
}
And this is respon from my code :
{
"result": true,
"data": [
{
"date": "2020-07-05",
"data": {
"id": "9924243",
"date_trx": "2020-07-05 07:03:58",
"user": "User A",
...
}
},
{
"date": "2020-06-01",
"data": {
"id": "9924243",
"date_trx": "2020-06-01 07:03:58",
"user": "User A",
...
}
},
{
"date": "2020-06-01",
"data": {
"id": "9924243",
"date_trx": "2020-06-01 07:03:58",
"user": "User A",
...
}
}
]
}
The respon from my code is not like my wishes, maybe you all can help me for wishes response
Iterate over results, add to your result a basic structure with 'date' and 'detail' under the date key if it doesnt exist and just add every row to correct 'detail'.
<?php
$db = new mysqli("localhost", "zz", "zz", "zz");
$query = "SELECT * FROM transaction ORDER BY date ASC";
$result = $db->query($query);
$data = [];
while($row = $result->fetch_assoc()) {
$date = new DateTime($row['tgl']);
if (!isset($data[$date->format('Y-m-d')])) {
$data[$date->format('Y-m-d')] = [
'date' => $date->format('j F Y'),
'detail' => [],
];
}
$data[$date->format('Y-m-d')]['detail'][] = [
'id' => $row['rid'],
'date_trx' => $date->format('d-m-Y H:i:s'),
'user' => $row['user'],
'price' => $row['price'],
'product_id' => $row['product'],
'quantity' => $row['quantity'],
];
}
$data = array_values($data);
var_dump(json_encode($data, JSON_PRETTY_PRINT));
Result:
string(892) "[
{
"date": "1 June 2020",
"detail": [
{
"id": "1",
"date_trx": "01-06-2020 15:22:54",
"user": "User A",
"price": "500",
"product_id": "Product A",
"quantity": "2"
},
{
"id": "2",
"date_trx": "01-06-2020 17:22:54",
"user": "User B",
"price": "500",
"product_id": "Product H",
"quantity": "2"
}
]
},
{
"date": "2 June 2020",
"detail": [
{
"id": "3",
"date_trx": "02-06-2020 15:22:54",
"user": "User A",
"price": "500",
"product_id": "Product A",
"quantity": "2"
}
]
}
]"
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
)));
}
?>
I want JSON object as follows in that personal, address and itm have sequence of json object.
{
"id": "1",
"state": "12",
"personal": [
{
"name": "abc",
"contact":"1111111"
"address": [
{
"line1": "abc",
"city": "abc",
"itm": [
{
"num": 1,
"itm_detatils": {
"itemname": "bag",
"rate": 1000,
"discount": 0,
}
}
],
"status": "Y"
}
]
}
]
}
But I am getting result as follows in that I want json array at address and itm_details.
{
"id": "1",
"state": "12",
"personal": [
{
"name": "abc",
"contact": "1111111",
"address": {
"line1": "abc",
"city": "abc",
"itm": {
"inum": "1",
"itm_detatils": {
"itemname": "bag",
"rate": 1000,
"discount": 0
}
},
"status": "Y"
}
}
]
}
My PHP Code is as follow:
In that I am creating simple array and after that array inside array but during encoding to json it's not showing sequence of json object.
$a=array();
$a["id"]="1";
$a["state"]="12";
$a["personal"]=array();
$a["personal"][]=array(
"name"=>"abc",
"contact"=>"1111111",
"address"=>array(
"line1"=>"abc",
"city"=>"abc",
"itm"=>array(
"inum"=>"1",
"itm_detatils"=>array(
"itemname"=>"bag",
"rate"=>1000,
"discount"=>0,
),
),
"status"=>"Y",
),
);
echo json_encode($a);
Thanks in advance.
Add one more array
//...
"address" => array(
array(
"line1"=>"abc",
"city"=>"abc",
// ...
),
)
Below is json code where i have o display its values. How to fetch the output as given below
$jsondata = '{
"flowers": [
{
"id": "1",
"name": "Le Grand Bouquet Blanc",
"price": "65",
"currency": "euro"
},
{
"id": "2",
"name": "Roses",
"price": "33",
"currency": "euro"
},
{
"id": "3",
"name": "Mandarine",
"price": "125",
"currency": "euro"
}
]
}';
Output should come like this
Name : Le Grand Bouquet Blanc, Price : 65
Name : Roses, Price : 33
Name : Mandarine, Price : 125
Total: 223 Euro
Any Help?
JSON decode, loop through the data and output the required text like so:
$data = json_decode($jsondata);
$total = 0;
foreach($data->flowers as &$datum) {
printf('Name : %s, Price: %d'.PHP_EOL, $datum->name, $datum->price);
$total += $datum->price;
}
printf('Total: %d Euro'.PHP_EOL, $total);
Read up on some basic PHP functions/concepts:
http://php.net/manual/en/function.json-decode.php
http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/function.printf.php
http://php.net/manual/en/function.echo.php
http://php.net/manual/en/language.operators.arithmetic.php
Try using json_decode() with true as second attribute to convert JSON it into array first.Then use foreach loop and get desired result.
<?php
$jsondata = '{
"flowers": [
{
"id": "1",
"name": "Le Grand Bouquet Blanc",
"price": "65",
"currency": "euro"
},
{
"id": "2",
"name": "Roses",
"price": "33",
"currency": "euro"
},
{
"id": "3",
"name": "Mandarine",
"price": "125",
"currency": "euro"
}
]
}';
$array = json_decode($jsondata,true);
//print_r($array);
$sum = 0;
foreach($array['flowers'] as $flowers)
{
echo "Name : ".$flowers['name'].",Price : ".$flowers['price'].PHP_EOL;
$sum+=$flowers['price'];
$currency = $flowers['currency'];
}
echo "Total:".$sum." ".$currency;
Try this.
$jsondata = '{
"flowers": [
{
"id": "1",
"name": "Le Grand Bouquet Blanc",
"price": "65",
"currency": "euro"
},
{
"id": "2",
"name": "Roses",
"price": "33",
"currency": "euro"
},
{
"id": "3",
"name": "Mandarine",
"price": "125",
"currency": "euro"
}
]
}';
$data = json_decode($jsondata,true);
echo "Name : " . $data['flowers'][0]['name'] . ' , Price: ' . $data['flowers'][0]['price'] ;