I need values from my database to plot a graph.
I have multiple lines I want to plot on the same graph.
I need the values, for each line, in the following form, for as many different $dates there are in the database:
$graph_points1 = array(array($date, $value), array($date, $value), array($date, $value));
I have a query to get the data from the database:
$data = $wpdb->get_results($wpdb->prepare( "SELECT * FROM `wp_graph_info` ORDER BY DATE ASC"));
If I use the following code:
foreach($data as $datas){
$list_name = $datas->list_name;
$date = $datas->date;
$value = $datas->subscriber_count;
if($list_name == 'line1'){
$result = array(array($date,$value));}}
print_r($result); will give:
Array ( [0] => Array ( [0] => 2015-05-16 [1] => 131 ) )
Array ( [0] => Array ( [0] => 2015-05-17 [1] => 133 ) )
Array ( [0] => Array ( [0] => 2015-05-18 [1] => 137 ) )
which is almost what I want.
I need to have the results as:
$graph_points1 = array(array(2015-05-16, 131), array(2015-05-17, 133), array(2015-05-18, 137));
how to I put it in the above form?
Also I can't plot the date on the x-axis. How do I only retrieve the 'day' value so I have:
$graph_points1 = array(array(16, 131), array(17, 133), array(18, 137));
Also if there a way to loop through all th $list_names (I have 7 different lists, so my graph will plot 7 lines) or do I need to use an if() statement for each one?
$result = [];
foreach($data as $datas){
$list_name = $datas->list_name;
$date = $datas->date;
$value = $datas->subscriber_count;
list($year, $month, $day) = explode('-', $date);
$result[$list_name][] = array($day,$value);
}
echo "<pre>";var_dump($result);echo "</pre>";
Related
Hi I have two multidimensional arrays in PhP and I am trying to create a new array which is flatter.
The first array is called weeksBooked and has a structure like below:
Array
(
[0] => Array
(
[periodweekno] => 27
)
[1] => Array
(
[periodweekno] => 28
)
[2] => Array
(
[periodweekno] => 29
)
)
The second one is called bookings . This stores the day a child was booked for that particular week.
Array
(
[0] => Array
(
[periodDayName] => Monday
)
[1] => Array
(
[periodDayName] => Tuesday
)
[2] => Array
(
[periodDayName] => Thursday
)
[3] => Array
(
[periodDayName] => Friday
)
)
I am trying to merge both the arrays and check if the perioddayName is Monday then in the "new" merged array I can show it as "monday"=> 0 and if not then show it as "monday"=> 1. I would like to repeat it for each "workday (i.e. monday - friday).
I apologise in advance if I am not explaining it well but this is what I am trying to achieve is a structure that I can bind to a table:
{Weekno:27, Monday:1,Tuesday:0,Wednedsay:1,Thursday:1,Friday:0
Weekno:28, Monday:0,Tuesday:0,Wednesday:1, Thursday:0,Friday:1}
This is my attempt so far but I just can't get it to flatten it :
$result = array();
foreach ($weeksbooked as $week) {
$sql = "SELECT periodDayName FROM Attendance WHERE weekno = ". $week['periodweekno'];
$bookings = $this->db->RawQuery($sql,null);
// print_r($bookings);
foreach ($bookings as $booking) {
$daysbooked= array();
if($booking['periodDayName'] == 'Monday'){
$daysbooked['monday'] = 0;
}else{
$daysbooked['monday'] = 1;
}
if($booking['periodDayName'] == 'Tuesday'){
$daysbooked['tuesday'] = 0;
}else{
$daysbooked['tuesday'] = 1;
}
.....
array_push($weeksbooked,$daysbooked)
}
array_push($result,$weekbooked)
Perhaps something like this?
$result = array();
foreach ($weeksbooked as $week) {
$sql = "SELECT periodDayName FROM Attendance WHERE weekno = ". $week['periodweekno'];
$bookings = $this->db->RawQuery($sql,null);
// print_r($bookings);
$thisweek = array('Weekno' => $week['periodweekno'],
'Monday' => 0,
'Tuesday' => 0,
'Wednesday' => 0,
'Thursday' => 0,
'Friday' => 0
);
foreach ($bookings as $booking) {
$thisweek[$booking['periodDayName']] = 1;
}
$result[] = $thisweek;
}
print_r($result);
It should produce an output something like what you are looking for. Without the raw data in a table it's hard to be certain.
This question is not a duplicate of other. it is different,This is current code, I am trying to sum the values of a array based on the same key value of date.
foreach ($TablesArr as $tr) {
$criteria = new CDbCriteria;
$criteria->select = 'date,mal';
$Arr1 = $tr::model()->findAll($criteria);
$array_1 = array();
foreach ($Arr1 as $a1) {
$array_1['date'] = $a1['date'];
$array_1['mal'] = $a1['mal'];
}
}
My Current output is:
Array
(
[date] => 2015-11-00
[mal] => 35
)
Array
(
[date] => 2015-12-00
[mal] => 20
)
Array
(
[date] => 2016-01-00
[mal] => 30
)
Array
(
[date] => 2016-01-00
[mal] => 10
)
Array
(
[date] => 2015-11-00
[mal] => 50
)
If the date is same, then sum the value of mal in the array. For example, In the above array, the date 2015-11-00 appears twice or more than twice (5 or 10 times etc) then sum all of the values of it for that date. Currently it appears twice so for 2015-11-00 the mal values will be 35+50=85. I want my output to be like this below:
Array
(
[date] => 2015-11-00
[mal] => 85
)
Array
(
[date] => 2015-12-00
[mal] => 20
)
Array
(
[date] => 2016-01-00
[mal] => 40
)
I have tried:
$result = array();
foreach($Arr1 as $data) {
$result[ $data['date'] ] += $data['mal'];
}
Your $array_1 variable doesn't contain all the values from the original $Arr1 array. You're overwriting the same elements each time through the loop, so it just contains the last item from $Arr1. These lines:
$array_1['date'] = $a1['date'];
$array_1['mal'] = $a1['mal'];
should be:
$array_1[] = array('date' => $a1['date'], 'mal' => $a1['mal']);
Another problem is that you're resetting $array_1 each time through the outer loop.
You can also use array_merge to combine the arrays, instead of the loop:
$array_1 = array();
foreach ($TablesArr as $tr) {
$criteria = new CDbCriteria;
$criteria->select = 'date,mal';
$Arr1 = $tr::model()->findAll($criteria);
$array_1 = array_merge($array_1, $Arr1);
}
You can use one of the solutions in php group by SUM using multi dimensional array to create an associative array with the sums grouped by date. You can turn this into a 2-dimensional array with another loop:
$newresult = array();
foreach ($result as $date => $mal) {
$newresult[] = array('date' => $date, 'mal' => $mal);
}
DEMO
I have an sql query that returns the altitude of a place. I have exploded the result to separate longitude and latitude. The result is stored in array.
Now I want to create an array which should contain all the arrays returned by the explode function.
$sql_altitude = mysql_query("SELECT altitude FROM `navigatio_info`
WHERE bus_id='$bus_id'
AND driver_id ='$driver_id'
ORDER BY stop_no ASC
LIMIT 0 , 30");
while ($row = mysql_fetch_assoc($sql_altitude))
{
//echo $row['altitude'];
//$altitude=array();
$altitude=(explode("-",$row['altitude']));
print_r($altitude);
//$lat=array();
$lat=$altitude[0];
//print_r($lat);
echo '<br/>';
//$long=array();
$long=$altitude[1];
//print_r($long);
//echo '<br/>';
}
below is a static array defined:
<?php
$phpArray = array(array('Vadodara',22.3000,73.2000,5),
array('Valsad',20.6300,72.9300,2),
array('Thane',19.1724,72.9570,1));
)?>
I want $phpArray to have dynamic values generated from the query above
Please use mysqli_* functions since mysql_* functions are old now.
$phpArray = array();
while ($row = mysql_fetch_assoc($sql_altitude))
{
/*
I assume $row['altitude'] contains something like below string
$row['altitude'] = "place-latitude-longitute-altitude"
*/
$phpArray[] = explode("-",$row['altitude']);
}
print_r($phpArray);
$sql_altitude = mysql_query("SELECT altitude FROM `navigatio_info` WHERE bus_id='$bus_id'AND driver_id ='$driver_id' ORDER BY stop_no ASC LIMIT 0 , 30");
$phparray = array();
while ($row = mysql_fetch_assoc($sql_altitude))
{
$altitude=(explode("-",$row['altitude']));
$lat=$altitude[0];
$long=$altitude[1];
$phparray = array($lat,$lat);
}
echo "<pre>";
print_r($phparray)
echo "<pre>";
Please check above code:
as i understand your requirement use the following code.
$phpArray = array();
while ($row = mysql_fetch_assoc($sql_altitude)) {
$altitude=(explode("-",$row['altitude']));
$phpArray[]= $altitude;
}
print"<pre>";
print_r($phpArray);
print"</pre>";
above code will generate following array.
Array
(
[0] => Array
(
[0] => Vadodara
[1] => 22.3000
[2] => 73.2000
[3] => 5
)
[1] => Array
(
[0] => Valsad
[1] => 20.6300
[2] => 72.9300
[3] => 2
)
[2] => Array
(
[0] => Thane
[1] => 19.1724
[2] => 72.9570
[3] => 1
)
)
Hope this helps.
I have the following array of dates and places - basically each date will need to allow for multiple places. I am trying to display the array below into something like the following format:
20140411
Basingstoke
Salisbury
20140405
Basingstoke
20140419
Salisbury
... and so on
The array:
Array
(
[20140411] => Array
(
[0] => Array
(
[0] => Basingstoke
)
[1] => Array
(
[0] => Salisbury
)
)
[20140405] => Array
(
[0] => Array
(
[0] => Basingstoke
)
)
[20140419] => Array
(
[0] => Array
(
[0] => Salisbury
)
)
[20140427] => Array
(
[0] => Array
(
[0] => Basingstoke
)
)
)
I believe I'm close, but I have always had some sort of mental block when it comes to working with arrays/keys etc. I am trying to do a nested foreach loop, which displays the dates fine, but am just getting "Array" outputted for the locations:
foreach ($dates as $date => $dateKey) {
// Format the date
$theDate = DateTime::createFromFormat('Ymd', $date);
$theFormattedDate = $theDate->format('d-m-Y');
echo '<h4>'.$theFormattedDate.'</h4>';
foreach ($dateKey as $key => $venue) {
echo $venue;
}
}
Can someone spot where I'm going wrong here?
EDIT:
Here is where the arrays are being created, if that helps?
$dates = array();
while ( have_rows('course_date') ) : the_row();
$theVenue = get_sub_field('venue');
// Use the date as key to ensure values are unique
$dates[get_sub_field('date')][] = array(
$theVenue->post_title
);
endwhile;
In your case venue is an array.
It's always an array with the only element you can address as [0].
Thus...
foreach ($dates as $date => $dateKey) {
// Format the date
$theDate = DateTime::createFromFormat('Ymd', $date);
$theFormattedDate = $theDate->format('d-m-Y');
echo '<h4>'.$theFormattedDate.'</h4>';
foreach ($dateKey as $key => $venue) {
echo $venue[0];
}
}
Or, in case you can have multiple venues in that last-level array, you can re-write the inner foreach adding another one:
foreach ($dates as $date => $dateKey) {
// Format the date
$theDate = DateTime::createFromFormat('Ymd', $date);
$theFormattedDate = $theDate->format('d-m-Y');
echo '<h4>'.$theFormattedDate.'</h4>';
foreach ($dateKey as $key => $venues) {
foreach($venues as $v) {
echo $v;
}
}
}
Places are nested 1 level deeper, you need one more foreach.
Never mind, that other guy said this plugin is supposed to work like that :)
I am working within a foreach loop and PARTS my code looks like this:
foreach ($query->rows as $row) {
$myarray = explode(",",$row['text']);
print_r($myarray);
}
The Output result of the above is this:
Array
(
[0] = Charcoal
[1] = Natural Gas
[2] = Combo
)
Array
(
[0] = Charcoal
[1] = Propane
[2] = Combo
)
Array
(
[0] = Charcoal
[1] = Propane
[2] = Natural Gas
[3] = Combo
)
Array
(
[0] = coal
)
Array
(
[0] = Natural Gas
[1] = Wood
)
Yes I see there are similar questions to this. But none of their answers seem to work for me. I'm thinking it might be because I am working inside an foreach loop. Either way, I was wondering if there was a way to get my output above to look like this:
Array
(
[0] = Charcoal
[1] = Natural Gas
[2] = Combo
)
Array
(
[0] = Propane
)
Array
(
[0] = Coal
)
Array
(
[0] = wood
)
All the duplicates gone, without loosing the formatting of this array. Code I have tried.. but "maybe" wrong was:
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
EDIT for Sharanya Dutta:
I have alot of other code, but basically this is where Im trying to use it.
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
if($diff !== array()) print_r($diff);
$arr = array_merge($arr, $_arr);
$output[$row['attribute_id']]['values'][] = $diff; // <--- USE IT HERE
}
Use an array ($arr in the following code) to store the values and print_r only those values which are different from the already stored values:
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
if($diff !== array()) print_r($diff);
$arr = array_merge($arr, $_arr);
}
DEMO
You may even use $diff after the last line in the foreach loop:
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
$arr = array_merge($arr, $_arr);
if($diff !== array()) print_r($diff);
}
DEMO
As you iterate the result set rows and explode the text string, filter the individual values in the current row against all values in all previously encountered rows.
If there are any individual values encountered for the first time, then save the unique values of that row as a new row in the result array.
Code: (Demo)
$resultSet = [
['text' => 'Charcoal,Natural Gas,Combo'],
['text' => 'Charcoal,Propane,Combo'],
['text' => 'Charcoal,Propane,Natural Gas,Combo'],
['text' => 'coal'],
['text' => 'Natural Gas,wood'],
];
$result = [];
foreach ($resultSet as $row) {
$clean = array_diff(
explode(',', $row['text']),
...$result
);
if ($clean) {
$result[] = array_values($clean);
}
}
var_export($result);
Output:
array (
0 =>
array (
0 => 'Charcoal',
1 => 'Natural Gas',
2 => 'Combo',
),
1 =>
array (
0 => 'Propane',
),
2 =>
array (
0 => 'coal',
),
3 =>
array (
0 => 'wood',
),
)