I have a problem , I'm just a newbie in programming and a bit low on logical problems. I want to generate an array values from a MySQL query result and it has to be nested.
My Actual Codes that i've been working on:
<?php
$mostSold_arr = array();
$subData_array = array();
$day_arr = array();
$data = array();
// Connect to MySQL
$link = new mysqli( 'localhost', 'root', '', 'db' );
if ( $link->connect_errno ) {
die( "Failed to connect to MySQL: (" . $link->connect_errno . ") " . $link->connect_error );
}
$fetch_data = mysqli_query($link, "SELECT products.id as prodID, title, SUM(total_price) as value, orders.order_date as date FROM products LEFT JOIN order_details ON order_details.product_id=products.id LEFT JOIN orders ON orders.id=order_details.order_id GROUP BY order_details.product_id ORDER BY value DESC LIMIT 2 ") or die(mysqli_error($link));
while ($row_mainData = mysqli_fetch_assoc($fetch_data)) {
$mostSold_arr['category'] = $row_mainData['title'];
$mostSold_arr['value'] = $row_mainData['value'];
$prod_id['prodID'] = $row_mainData['prodID'];
$mostSold_arr['url'] = "#";
$mostSold_arr['description'] = "click to drill-down";
$mostSold_arr['data'] = array();
$fetch_subData = mysqli_query($link, "SELECT title, SUM(total_price) as value, MONTHNAME(orders.order_date) as date FROM products LEFT JOIN order_details ON order_details.product_id=products.id LEFT JOIN orders ON orders.id=order_details.order_id WHERE order_details.product_id=" . $prod_id['prodID'] ." GROUP BY title, date ORDER BY order_date LIMIT 3 ") or die(mysqli_error($link));
while ($row_subData = mysqli_fetch_assoc($fetch_subData)) {
$subData_arr['category']=$row_subData['date'];
$subData_arr['value']=$row_subData['value'];
$day_arr['data'] = array();
array_push($mostSold_arr['data'],$subData_arr);
$fetch_subDataDay = mysqli_query($link, "SELECT title, SUM(total_price) as value, DATE_FORMAT(orders.order_date, '%M-%d') as date FROM products LEFT JOIN order_details ON order_details.product_id=products.id LEFT JOIN orders ON orders.id=order_details.order_id WHERE order_details.product_id=" . $row_mainData['prodID'] ." AND DATE_FORMAT(orders.order_date, '%M-%d') LIKE '%March%' GROUP BY date ORDER BY order_date LIMIT 3 ") or die(mysqli_error($link));
while ($row_subDataDay = mysqli_fetch_assoc($fetch_subDataDay)) {
$subDataDay_arr['category']=$row_subDataDay['date'];
$subDataDay_arr['value']=$row_subDataDay['value'];
//array_push($day_arr['data'],$subDataDay_arr);
if($subData_arr['category'] == 'March'){
array_push($mostSold_arr['data'],$subDataDay_arr);
}
//array_push($day_arr['data'],$subDataDay_arr);
//var_dump($subData_arr);
}
}
array_push($data, $mostSold_arr);
}
$jsonData = json_encode($data, JSON_PRETTY_PRINT);
$fp = fopen('dataColMultiNested.json', 'w');
fwrite($fp, $jsonData);
fclose($fp);
die('<pre>' . print_r($jsonData, 1));
mysqli_close($link);
?>
The Actual Output of the code above:
[
{
"category": "ACER E5-473-53C0",
"value": "2455200.00",
"url": "#",
"description": "click to drill-down",
"data": [
{
"category": "March",
"value": "809100.00"
},
{
"category": "March-02",
"value": "27900.00"
},
{
"category": "March-03",
"value": "27900.00"
},
{
"category": "March-04",
"value": "55800.00"
},
{
"category": "April",
"value": "781200.00"
},
{
"category": "May",
"value": "418500.00"
}
]
},
{
"category": "ACER ASPIRE E5-551G-F57K LAPTOP",
"value": "2339220.00",
"url": "#",
"description": "click to drill-down",
"data": [
{
"category": "March",
"value": "449850.00"
},
{
"category": "March-02",
"value": "29990.00"
},
{
"category": "March-03",
"value": "59980.00"
},
{
"category": "March-07",
"value": "59980.00"
},
{
"category": "April",
"value": "689770.00"
},
{
"category": "May",
"value": "779740.00"
}
]
}
Expected Output(it should be like this)
[
{
"category": "ACER E5-473-53C0",
"value": "2455200.00",
"url": "#",
"description": "click to drill-down",
"data": [
{
"category": "March",
"value": "809100.00",
"data": [
{
"category": "March-02",
"value": "27900.00"
},
{
"category": "March-03",
"value": "27900.00"
},
{
"category": "March-04",
"value": "55800.00"
}
]
},
{
"category": "April",
"value": "781200.00"
},
{
"category": "May",
"value": "418500.00"
}
]
},
{
"category": "ACER ASPIRE E5-551G-F57K LAPTOP",
"value": "2339220.00",
"url": "#",
"description": "click to drill-down",
"data": [
{
"category": "March",
"value": "449850.00",
"data": [
{
"category": "March-02",
"value": "29990.00"
},
{
"category": "March-03",
"value": "59980.00"
},
{
"category": "March-07",
"value": "59980.00"
}
]
},
{
"category": "April",
"value": "689770.00"
},
{
"category": "May",
"value": "779740.00"
}
]
}
]
I'm working on this for about 2 nights or more but can find the right solution for my problem.
I hoping that you guys can help me. Thanks.
This is a totally refunded answer, based on the information which lacked in your question and its tags: your desired result is in JSON format (but I must admit that your representation complied with it).
In PHP, you must first create an equivalent array that will look like this:
[
0 => [
"year" => "2016",
"data" => [
0 => [
"month" => "Dec",
"data" => [
0 => [
"day": "Dec 04",
],
],
],
],
],
]
It can be built with something not far from your initial code:
$fetch_data1 = "Select * From tbl1";
$year = [];
while($row_year = mysqli_fetch_assoc($fetch_data1)){
$year['year'] = $row_year['year'];
$fetch_data2 = "Select * From tbl2";
/* my query needs to loop inside because
it will contain condition depends on the retrieved data row */
$data = [];
while($row_month = mysqli_fetch_assoc($fetch_data2)){
$data['month'] = $row_month['month'];
$fetch_data3 = "Select * From tbl3";
/* my query needs to loop inside because
it will contain condition depends on the retrieved data row */
$day = [];
while($row_day = mysqli_fetch_assoc($fetch_data3)){
$day['day'] = $row_month['month'] . ' ' . $row_day['day'];
}
$data['data'] = $day;
}
$year[] = $data;
}
Related
I can't properly use INNER JOIN. This is the actual return output via json on php.
[
{
"id": "1",
"itinerary_customer_id": "856",
"datetime_created": "2020-04-20 19:54:16",
"documents": [
{
"id": "1",
"itinerary_id": "1",
"datetime_created": "2020-04-20 22:51:12"
},
{
"id": "2",
"itinerary_id": "1",
"datetime_created": "2020-04-20 22:51:12"
},
]
},
{
"id": "2",
"itinerary_customer_id": "857",
"datetime_created": "2020-04-20 19:54:16",
"documents": [
{
"id": "3",
"itinerary_id": "2",
"datetime_created": "2020-04-20 22:51:12"
},
{
"id": "4",
"itinerary_id": "2",
"datetime_created": "2020-04-20 22:51:12"
},
]
}
]
Its look like array json and there's possible array inside each data.
Here's my existing code.
$sql = "SELECT * FROM itinerary INNER JOIN itinerary_documents ON itinerary_documents.itinerary_id = itinerary.id WHERE itinerary_customer_id = '".$customer_id."' ";
$result = $mysql->query($sql);
if ($result->num_rows > 0) {
while ($row[] = $result->fetch_assoc()) {
$item = $row;
$json = json_encode($item);
}
}else{
$item = array("error"=> true, "message"=> "No Itinerary found.");
$json = json_encode($item);
}
echo $json;
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.
I am working on fetching JSON file from the database, which has two table semone with attributes id, semester, cname and table courses with attributes coname and credit.
Code I am writing in php is following.
main.php
<?php
$user = "root";
$password = "";
$database = "scheduler";
$con = mysqli_connect("localhost", $user, $password, $database) or die ("Unable to connect");
$query = "SELECT semone.userid AS id, semone.semester AS semester, semone.cname AS name, courses.credit AS value
FROM semone
INNER JOIN courses
ON semone.cname = courses.coname" ;
$result = mysqli_query($con,$query)or die ("Unable to connect");
$info = array();
$test = array();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$row['xyz'] = array(
'name'=> $row['name'],
'value'=> $row['value']
);
$info[$row['id']]['children'][$row['semester']]['children'][]= $row['xyz'];
}
$data = json_encode(($info));
echo $data;
?>
I want to get JSON file as seen in the following code, but I am getting something like this.
output.json
{
"12345": {
"children": {
"first": {
"children": [{
"name": "C101",
"value": 100
},
{
"name": "C102",
"value": 100
}]
},
"second": {
"children": [{
"name": "C103",
"value": 50
}, {
"name": "C104",
"value": 100
}, {
"name": "C105",
"value": 100
}]
},
"third": {
"children": [{
"name": "C106",
"value": 50
}]
}
}
}
}
But this is what I am expecting.
expected.json
{
"id": 12345,
"children": [{
"semester": "first",
"children": [{
"name": "C101",
"value": 100
},
{
"name": "C102",
"value": 100
}]
}, {
"semester": "second",
"children": [{
"name": "C103",
"value": 50
}, {
"name": "C104",
"value": 100
}, {
"name": "C105",
"value": 100
}]
}, {
"semester": "third",
"children": [{
"name": "C106",
"value": 50
}]
}
}
You probably should build your array in a different way:
$info[] = array(
array('id' => $row['id']),
'children' => array(
'semester' => $row['semester'],
'children' => $row['xyz']
)
);
I am trying to iterate both index of JSON(Players and Buildings), so that i can a get new result in jQuery
I have two index of JSON one having information of Players and second index having information of Building related Player.
I want to Parse it so that i can get Player and its building name.
My Actual JSON result
{
"Players": [
{
"id": "35",
"building_id": "8",
"room_num": "101",
},
{
"id": "36",
"building_id": "9",
"room_num": "102",
},
{
"id": "37",
"building_id": "10",
"room_num": "103",
},
{
"id": "38",
"building_id": "11",
"room_num": "104",
}
],
"Buildings": [
{
"id": "8",
"name": "ABC"
},
{
"id": "9",
"name": "DEF"
},
{
"id": "10",
"name": "GHI"
},
{
"id": "11",
"name": "JKL"
}
]
}
Need this
"information": [
{
"player_id": "35",
"Buildings_name": "ABC"
},
{
"player_id": "36",
"Buildings_name": "DEF"
},
{
"player_id": "37",
"Buildings_name": "GHI"
},
{
"player_id": "38",
"Buildings_name": "JKL"
}
]
}
Here you go, this go for each player and check if there are buildings and will map them to new structure. This will not filter values for buildings that do not have mapping to players, and will not include the buildings with no players.
var x = {
"Players": [
{
"id": "35",
"building_id": "8",
"room_num": "101",
},
{
"id": "36",
"building_id": "9",
"room_num": "102",
},
{
"id": "37",
"building_id": "10",
"room_num": "103",
},
{
"id": "38",
"building_id": "11",
"room_num": "104",
}
],
"Buildings": [
{
"id": "8",
"name": "ABC"
},
{
"id": "9",
"name": "DEF"
},
{
"id": "10",
"name": "GHI"
},
{
"id": "11",
"name": "JKL"
}
]
};
var res = $.map(x.Players, function(item) {
return {
player_id: item.id,
building_name: $.grep(x.Buildings, function(i) {
return i.id == item.building_id
}).length != 0 ? $.grep(x.Buildings, function(i) {
return i.id == item.building_id
})[0].name : undefined
}
})
and if you want to filter values that do not have relationships e.g INNER join
var resInnerJoin = $.grep($.map(x.Players, function(item) {
return {
player_id: item.id,
building_name: $.grep(x.Buildings, function(i) {
return i.id == item.building_id
}).length != 0 ? $.grep(x.Buildings, function(i) {
return i.id == item.building_id
})[0].name : undefined
}
}), function(it) {
return it.building_name != undefined
})
If you need it in PHP :
$json = '{...}';
// create and PHP array with you json data.
$array = json_decode($json, true);
// make an array with buildings informations and with building id as key
$buildings = array();
foreach( $array['Buildings'] as $b ) $buildings[$b['id']] = $b;
$informations = array();
for ( $i = 0 ; $i < count($array['Players']) ; $i++ )
{
$informations[$i] = array(
'player_id' => $array['Players'][$i]['id'],
'Buildings_name' => $buildings[$array['Players'][$i]['building_id']]['name']
);
}
$informations = json_encode($informations);
var_dump($informations);
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 !