how to prepare data format to show in c3js chart? - php

I want to show percent of department depend on date in c3js chart with timeseries.
I have four department id, and I query the result like this.
$dept_id_arr = array();
$date_arr = array();
$percent_arr = array();
$sql = ........;
$rsl = mysql_query($sql);
while($get = mysql_fetch_assoc($rsl)){
$date_arr[] = $get['date'];
$dept_id_arr[] = $get['department_id'];
$percent_arr[] = $get['total_percent'];
}
When I print this data with var_dump(), I got like this,
string(66) "["2015-11-17","2015-11-17","2015-11-18","2015-11-20","2015-11-23"]"
string(22) "["1","3","1","1","2"]"
string(46) "["0.5700","0.0000","0.5700","0.0000","0.5700"]"
I want to change that value to like this,
[{
"date": "2015-11-17",
"department1": "0.5",
"department2": "0.9",
"department3": "4",
"department4": "3",
}, {
"date": "2015-11-18",
"department1": "0.5",
"department2": "0",
"department3": "0",
"department4": "0",
}, {
"date": "2015-11-19",
"department1": "0.5",
"department2": "0.3",
"department3": "5",
"department4": "2",
}]
because I need to show that data in c3js chart. But I have problem, when I change data to that format because of some date are same in array.

You can do all the things by this code:
<?php
$date = ["2015-11-17","2015-11-17","2015-11-18","2015-11-20","2015-11-23"];
$departmeent = ["1","3","1","1","2"];
$percentage = ["0.5700","0.0000","0.5700","0.0000","0.5700"];
$array = array();
for($i=0; $i<5;$i++)
{
if(array_key_exists($date[$i], $array))
{
$array[$date[$i]]['department'.$departmeent[$i]]= $departmeent[$i];
$array[$date[$i]]['per'.$departmeent[$i]]= $percentage[$i];
}
else
{
$array[$date[$i]] = array('department'.$departmeent[$i] => $departmeent[$i],
'per'.$departmeent[$i] => $percentage[$i]) ;
}
}
echo var_dump($array["2015-11-17"]["department1"]);
echo '<br><br><br><br><br><br>'.json_encode($array);
?>

Related

How to return json object with json array inside of it?

i have many to many relationship
like this :
Server version: 10.4.17-MariaDB
table colors(id,name).
table items(id,title....).
table item_color(id,items_id,color_id).
my query is like this :
SELECT items.*,colors.name FROM items,item_color,colors
where
items.id = item_color.item_id
and
colors.id = item_color.color_id
i use php function json_encode().
how to return this :
{
"id": "22",
"title": "my products 515151",
"descreption": "5454545455",
"price": "0.05",
"quantity": "2",
"date_added": "2021-01-29 14:37:24",
"primary_image": "http://localhost/ecomerce/uploads/1611927444hat.jpg",
"color": [
0 : "pink",
1 : "white"
]
}
instead if this:
"id": "22",
"title": "my products 515151",
"descreption": "5454545455",
"price": "0.05",
"quantity": "2",
"date_added": "2021-01-29 14:37:24",
"primary_image": "http://localhost/ecomerce/uploads/1611927444hat.jpg",
"color": "pink"
},
{
"id": "22",
"title": "my products 515151",
"descreption": "5454545455",
"price": "0.05",
"quantity": "2",
"date_added": "2021-01-29 14:37:24",
"primary_image": "http://localhost/ecomerce/uploads/1611927444hat.jpg",
"color": "red"
},
There's 2 way to do it:
If you want to keep your query, you must parse the data first before you parse it to json.
...
function regroup_color($data = array()){
$ret = array();
foreach($data as $d){
$id = $d['id'];
if(!isset($ret[$id])){
$color = $d['color'];
unset($d['color']);
$ret[$id] = $d;
$ret[$id]['color'][] = $color;
}else{
$ret[$id]['color'][] = $d['color'];
}
}
return $ret;
}
$data = regroup_color($data);
echo json_encode($data)
...
Or you could just...
make the query 2 part, first is for get all items, second is for get the colors for it
...
$query = "SELECT * FROM items";
// get the data here using query above
$data = {{result of query}};
foreach($data as $i => $d){
$id = $d['id'];
$query = "SELECT * FROM item_color JOIN colors ON item_color.color_id = colors.id";
// get the data here using query above
$colors = {{result of query}};
foreach($colors as color){
$data[$i]['color'][] = $color['name'];
}
}
echo json_encode($data)
...
i wanted to add also category so this is what i came with
function regroup_color($data = array(),$data2 = array()){
// array that will hold our data and we will return it later
$ret = array();
// fetch the data as d
foreach($data as $d){
//save the id
$id = $d['id'];
//make sure no id was set
if(!isset($ret[$id])){
// save the name of the color
$color = $d['color'];
unset($d['color']);
//save all the item data
$ret[$id] = $d;
// add color to color array
$ret[$id]['color'][] = $color;
}else{
// if wa alredy did all the above things just keep adding colors to color array
$ret[$id]['color'][] = $d['color'];
}
}
foreach($data2 as $d){
//save the id
$id = $d['id'];
//make sure no id was set
if(!isset($ret[$id])){
// save the name of the color
$category = $d['category'];
unset($d['category']);
$ret[$id] = $d;
$ret[$id]['category'][] = $category;
}else{
$ret[$id]['category'][] = $d['category'];
}
}
return $ret;
}
result :
"22": {
"id": "22",
"title": "my products 515151",
"descreption": "5454545455",
"price": "0.05",
"quantity": "2",
"date_added": "2021-01-29 14:37:24",
"primary_image": "http://localhost/ecomerce/uploads/1611927444hat.jpg",
"color": [
"black",
"white",
"pink",
"red",
"yellow"
],
"category": [
"buttom",
"hats",
"shoes"
]
}

How to get data in json form

Currently, I am making an API and I want the data in JSON format. But I am not able to get it. It is coming in normal form. But how to convert it into JSON. If I am writing json_encode($response) outside the loop then I am getting the data in json format but only one data.
If i wriing the json encode inside the loop then i am getting all the data but not in JSON form. How to solve this. I am not able to get the perfect solution for ths question.
$tsym = strtolower($_REQUEST['tsym']);
$time = strtolower($_REQUEST['time']);
$mil = $time;
$seconds = $mil / 1000;
$normal_date = date("Y-m-d H:i:s", $seconds);
$sql = "SELECT * FROM `forex` where pair='".$tsym."' and date >= '".$normal_date."' order by date limit 0,10";
$result = mysqli_query($conn, $sql);
$response = array();
while($rows = mysqli_fetch_assoc($result)){
$from_sym = $rows['pair'];
//if(!isset($response[$from_sym]))
{
$response[$from_sym] = $rows;
//echo json_encode($response, true);
//}
print_r( json_encode($response)); //this prints all the data but not
in json form
}
print_r( json_encode($response)); //this prints single data but in
json form
I want all the data but in json form. how to get it? Thank you for the help.
I want data like this:
{
"CHFJPY": {
"id": "33",
"pair": "CHFJPY",
"date": "2018-04-22 20:42:21",
"price": "110.413",
"change_rate": "0",
"fetched": "1"
}
},
{
"CHFJPY": {
"id": "75",
"pair": "CHFJPY",
"date": "2018-04-22 20:42:29",
"price": "110.413",
"change_rate": "0",
"fetched": "1"
}
},
{
"CHFJPY": {
"id": "117",
"pair": "CHFJPY",
"date": "2018-04-23 11:25:47",
"price": "110.585",
"change_rate": "0",
"fetched": "1"
}
},
{
"CHFJPY": {
"id": "159",
"pair": "CHFJPY",
"date": "2018-04-23 12:34:54",
"price": "110.816",
"change_rate": "0",
"fetched": "1"
}
},
{
"CHFJPY": {
"id": "201",
"pair": "CHFJPY",
"date": "2018-04-23 12:35:04",
"price": "110.825",
"change_rate": "0",
"fetched": "1"
}
}
But i am getting only one data.
You have to append your row to the final array $response in your while loop
$response = array();
while($rows = mysqli_fetch_assoc($result)){
$from_sym = $rows['pair'];
$res[$from_sym] = $rows;
$response[] = $res;
}
print_r(json_encode($response));
You need to move the json_encode into the outside of while loop
<?php
$tsym_escaped = mysqli_real_escape_string($conn, $_REQUEST['tsym']);
$date = date("Y-m-d H:i:s", $_REQUEST['time']/1000);
$sql = sprintf(
"SELECT * FROM `forex` WHERE `pain`='%s' AND `date`>='%s' ORDER BY `date` LIMIT 0,10",
$tsym_escaped,
$date
);
$result = mysqli_query($conn, $sql);
$response = array();
while($row = mysqli_fetch_assoc($result)){
$response[$row['pair']] = $row;
}
echo json_encode($response);
Also, the way you're passing the data into the SQL query is insecure and can lead into a SQL injection.
is not clear why you have not json so .. in more clear way try
while($rows = mysqli_fetch_assoc($result)){
$response[$rows['pair']] = $rows;
}
$myJSON = json_encode($response);
var_dump($myJSON);
this should buil a $reponse array with the related vleus for each 'pair' index
but could be you need all the rows result so try
while($rows = mysqli_fetch_assoc($result)){
$response[] = $rows;
}
$mySecondJSON = json_encode($response);
var_dump($mySecondJSON);
or
while($rows = mysqli_fetch_assoc($result)){
$response[] = $rows['pair'];
}
$myOtherJSON = json_encode($response);
var_dump($myOtherJSON);

Compare variable of two different array?

Here i want compare two array.
I have two tables one is CATEGORY and second is USER(in which selected multiple category is stored in this format , , , ).
but when the USER want to update their category at that time the earlier selected category should return checked 1 and which is not selected should return checked 0 and here is my code.
case 'cat':
$sql="SELECT category from nesbaty_user where user_id='".$user_id."'";
$qry_res=mysqli_query($con,$sql);
$response1 = array();
while ($array = mysqli_fetch_array($qry_res))
{
foreach (explode(',', $array['category']) as $cat)
{
$response1[]=array('category' => $cat);
$response['Selected_category'] = $response1;
}
}
$qry="SELECT cat_id,category,image_url FROM nesbaty_category";
$qry_res=mysqli_query($con,$qry);
$jsonData = array();
while ($array = mysqli_fetch_assoc($qry_res))
{
$jsonData[] = $array;
$response['category'] = $jsonData;
}
echo json_encode($response);
//echo json_encode(array('data1' =>$response1));
//
mysqli_close($con);
break;
and here is my fetched array from the database.
{
"Selected_category": [
{
"category": "5"
},
{
"category": "6"
},
{
"category": "9"
}
],
"category": [
{
"cat_id": "1",
"category": "Drug",
"image_url": "1.jpg"
},
{
"cat_id": "2",
"category": "Bars",
"image_url": "2.jpg"
},
{
"cat_id": "3",
"category": "Bars",
"image_url": "2.jpg"
},
{
"cat_id": "4",
"category": "Hair Saloon",
"image_url": "2.jpg"
}
]
}
This is for handle this same structure as You provided.
<?php
$response = [];
$sql = "SELECT category from nesbaty_user where user_id='".$user_id."'";
$qry_res = mysqli_query($con, $sql);
$selectedCategories = mysqli_fetch_array($qry_res);
$selectedCategories = explode(',', $selectedCategories['category']);
$qry = "SELECT cat_id,category,image_url FROM nesbaty_category";
$qry_res = mysqli_query($con, $qry);
while ($categories = mysqli_fetch_assoc($qry_res)) {
$categories['checked'] = (int)\in_array($categories['cat_id'], $selectedCategories);
$response[] = $categories;
}
echo json_encode($response);
mysqli_close($con);
If any error writes a comment, I'll fix it.

JSON array in array from SQL database using PHP

I have the following code:
$retarray = array();
$hoursarray = array();
$res = $this->mysqli->query("SELECT id, title, groupby FROM scheduler_activity WHERE gewerbe = '$this->gewerbe'");
while($row = $res->fetch_object()) {
$foo = $this->mysqli->query("SELECT dow, start, end FROM scheduler_businesshours WHERE activity = '$row->id'");
while($hours = $foo->fetch_object()){
$hoursarray[] = $hours;
}
$retarray[] = $row;
$retarray["businessHours"] = $hoursarray;
}
return $retarray;
And the following JSON output:
{
"0": {
"id": "1",
"title": "Spinning",
"groupby": "Trainingsgruppe"
},
"businessHours": [{
"dow": "[1,2,3]",
"start": "17:00:00",
"end": "18:00:00"
}, {
"dow": "[4,5]",
"start": "17:30:00",
"end": "18:30:00"
}],
"1": {
"id": "2",
"title": "Massage",
"groupby": "Trainingsgruppe"
},
"2": {
"id": "3",
"title": "Yoga",
"groupby": "Trainingsgruppe"
},
"3": {
"id": "4",
"title": "Dance Academy",
"groupby": "Trainingsgruppe"
}
}
So far it looks correct but I need to get rid of the leading numbers like 0, 1, 2, 3
That it will look like this plus the businessHours:
[{
"id": "1",
"title": "Spinning",
"groupby": "Trainingsgruppe"
}, {
"id": "2",
"title": "Massage",
"groupby": "Trainingsgruppe"
}, {
"id": "3",
"title": "Yoga",
"groupby": "Trainingsgruppe"
}, {
"id": "4",
"title": "Dance Academy",
"groupby": "Trainingsgruppe"
}]
What did I do wrong there?
Thank you!
As I understood about your code, we get business hour for each activity, so it's just a small change at line 10:
$retarray = array();
$hoursarray = array();
$res = $this->mysqli->query("SELECT id, title, groupby FROM scheduler_activity WHERE gewerbe = '$this->gewerbe'");
while($row = $res->fetch_object()) {
$foo = $this->mysqli->query("SELECT dow, start, end FROM scheduler_businesshours WHERE activity = '$row->id'");
while($hours = $foo->fetch_object()){
$hoursarray[] = $hours;
}
$row["businessHours"] = $hoursarray; // Change to this, swap line 10 & 11
$retarray[] = $row;
}
return $retarray;
Hope this helps.
You add two keys. One key is numeric the second is businessHours.
$retarray[] = $row;
$retarray["businessHours"] = $hoursarray;
For instance you can add it businessHours to $row
$row["businessHours"] = $hoursarray;
$retarray[] = $row;
Have you try array_values($array)?
$retarray = array();
$hoursarray = array();
$res = $this->mysqli->query("SELECT id, title, groupby FROM scheduler_activity WHERE gewerbe = '$this->gewerbe'");
while($row = $res->fetch_object()) {
$foo = $this->mysqli->query("SELECT dow, start, end FROM scheduler_businesshours WHERE activity = '$row->id'");
while($hours = $foo->fetch_object()){
$hoursarray[] = $hours;
}
$retarray[] = $row;
$retarray["businessHours"] = $hoursarray;
}
return array_values($retarray);

Merge results of single JSON output with PHP

I have a JSON array as per below:
{
"aaData": [
{
"Date_time": "23",
"traffic": "22",
"direction": "sent"
},
{
"Date_time": "24",
"traffic": "55",
"direction": "sent"
},
{
"Date_time": "25",
"traffic": "60",
"direction": "sent"
},
{
"Date_time": "26",
"traffic": "43",
"direction": "sent"
},
{
"Date_time": "27",
"traffic": "50",
"direction": "sent"
},
{
"Date_time": "23",
"traffic": "50",
"direction": "received"
},
{
"Date_time": "24",
"traffic": "42",
"direction": "received"
},
{
"Date_time": "25",
"traffic": "52",
"direction": "received"
},
{
"Date_time": "26",
"traffic": "47",
"direction": "received"
},
{
"Date_time": "27",
"traffic": "36",
"direction": "received"
}
]
}
What I'd like to do with it is combine all the results with the same date into a single entry - so for date_time 23 I want it to appear like this
"Date_time": "23",
"traffic-sent": "22",
"traffic-received": "50"
I'd like to do this with PHP if possible? The data is coming from two separate mySQL queries, coming from to different mySQL databases. I've tried combining the output of the query to do what I need (tried Joins and Unions) but can't get past the separation of the results as per my first example.
The part of the SQL query creating the JSON looks like this:
while($row = mysqli_fetch_assoc($result)) {
$model[$i]['Date_time'] = $row['the_day'];
$model[$i]['traffic'] = $row['traffic'];
$model[$i]['direction'] = $row['TABLE_NAME'];
$i++;
}
And the SQL looks like this:
(SELECT
DAY(`Time`) AS the_day,
count(accounts.accName) AS traffic,
"sent" AS TABLE_NAME
FROM
bss.ss_sent LEFT JOIN bss.accounts ON ss_sent.Customer = accounts.accName
WHERE
YEARWEEK(`Time`) = YEARWEEK(CURRENT_DATE)
AND
Customer != " "
AND
accShortName = "QRR"
GROUP BY
the_day)
UNION
(SELECT
DAY(Date_time) AS the_day,
count(AS_Task) AS traffic,
"received" AS TABLE_NAME
FROM
im_stats.as_counter
WHERE
AS_Task = "QRR3 Incoming"
AND
YEARWEEK(Date_time) = YEARWEEK(CURRENT_DATE)
GROUP BY
the_day
Order by the_day)
IF anyone can advise of a way to combine the results I'd very much appreciate it.
UPDATE:
This is how I've entered Populus's code:
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
$model[$i]['Date_time'] = $row['the_day'];
$model[$i]['traffic'] = $row['traffic'];
$model[$i]['direction'] = $row['TABLE_NAME'];
$i++;
}
$combined = array();
foreach ($model as $val) {
$date_time = $val['Date_time'];
if (!isset($combined[$date_time)) {
$combined[$date_time] = array(
'Date_time' => $date_time,
'traffic_sent' => 0,
'traffic_received' => 0,
);
}
if ('received' == $val['direction']) {
$combined[$date_time]['traffic_received'] += $val['traffic'];
} else {
$combined[$date_time]['traffic_sent'] += $val['traffic'];
}
}
header('Content-type: application/json');
print json_encode(array('aaData' => $combined), JSON_PRETTY_PRINT);
This could probably be done using SQL (which you haven't provided), but if you really want PHP:
$combined = array();
foreach ($model as $val) {
$date_time = $val['Date_time'];
if (!isset($combined[$date_time])) {
$combined[$date_time] = array(
'Date_time' => $date_time,
'traffic_sent' => 0,
'traffic_received' => 0,
);
}
if ('received' == $val['direction']) {
$combined[$date_time]['traffic_received'] += $val['traffic'];
} else {
$combined[$date_time]['traffic_sent'] += $val['traffic'];
}
}
Your desired array is now in $combined. If you don't want the keys, you can remove it:
$result = array_values($combined);
Try it this way:
while($row = mysqli_fetch_assoc($result)) {
if ($row['direction'] == 'sent')
$dt[$row['Date_time']]['traffic-sent'] += $row['traffic'];
elseif ($row['direction'] == 'recieved')
$dt[$row['Date_time']]['traffic-recieved'] += $row['traffic'];
}
foreach ($dt as $date) {
echo "Date_time: " . key($date) . ",<br/>" .
"traffic_sent: " . $date['traffic-sent'] . ",<br/>" .
"traffic-recieved: " . $date['traffic-recieved'] . "<br/><br/>";
}

Categories