I have a simple array which has been used before with no problems. Now I am trying to use it again and it is displaying nothing for text (Even in view source).
Array:
$month = Array(
1 => "January",
2 => "February",
3 => "March",
4 => "April",
5 => "May",
6 => "June",
7 => "July",
8 => "August",
9 => "September",
10 => "October",
11 => "November",
12 => "December"
);
Code:
function getMonthlyStats($comic_id) {
require "config.php";
$query = 'SELECT *, SUM(views) AS `views` FROM '.$db_tbl_stats.' WHERE '.$db_fld_stats_comic_id.'="'.$comic_id.'" GROUP BY '.$db_fld_stats_month.' ASC';
$r_query = mysql_query($query);
while ($result = mysql_fetch_array($r_query)) {
$percent = ($result[$db_fld_stats_views]/getTotalStats($comic_id))*100;
$m = number_format($result['month']);
echo '<tr>';
echo '<td width="100"> ';
echo $month[$m];
echo '</td>';
echo '<td width="400" class="bar"><div style="width: '.$percent.'%"></div>'.$result[$db_fld_stats_views].' Views</td>';
echo '<td>'.number_format($percent).'%</td>';
echo '</tr>';
}
}
$m returns a number from 1-12 which obviously represents a month.
If you need more info I will be happy to explain more. Any help is greatly appreciated! Going on 4 hours writing and my eyes are tired.
You need to add global $month; to your function, or use $GLOBALS['month'] instead of $month.
This is called "variable scope". See http://php.net/manual/en/language.variables.scope.php for more details.
Related
This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 3 years ago.
I am getting an array in PHP as:
Array
(
[1] => 2019
[2] => 5
[3] => 7
[4] => 0
)
where [1] is always the year, [2] is always the month and [3] is always the date.
How can I convert this array to date("Y-m-d") format?
Assuming this data input:
$data = [null, 2019, 5, 7, 0];
Using DateTime
$dt = new DateTime(sprintf( "%04d-%02d-%02d", $data[1], $data[2],
$data[3]));
echo $dt->format('Y-m-d') . "\n";
Using Sprintf
// use this if you really trust the data
$dt = sprintf( "%04d-%02d-%02d", $data[0], $data[1], $data[2]);
echo $dt . "\n";
Using Carbon
// Carbon is a fantastic Date and Time class -> https://carbon.nesbot.com/
$dt = \Carbon\Carbon::create($data[0], $data[1], $data[2], 0, 0, 0);
echo $dt->format('Y-m-d') . "\n";
you can use DateTime
$timeArray = [2019,5,7,0];
$dateTime = new DateTime(printf( "%d-%d-%d", $timeArray[0],$timeArray[1],$timeArray[2] ));
echo $dateTime->format('Y-m-d'); // output: 2019-05-07
Do it like this
$arr = array( '2019', '5', '7', '0' );
echo date('Y-m-d',strtotime("$arr[0]/$arr[1]/$arr[2]"));
Although it's possible to just concatenate those values into a string and then let PHP parse that string into the Y-m-d format, I personally think mktime() is the better solution:
echo date("Y-m-d", mktime(0, 0, 0, $arr[2], $arr[3], $arr[1]));
// 2019-05-07
This removes the risk of PHP accidentally interpreting the day and month in the wrong order.
You might simply use concat and join them into a string:
$arr = array(
"1" => "2019",
"2" => "5",
"3" => "7",
"4" => "0",
);
$datetime_format = $arr["1"] . "-" . $arr["2"] . "-" . $arr["3"];
var_dump($datetime_format);
Output
string(8) "2019-5-7"
If you wish to have a 4-2-2 format, this might work:
$arr = array(
"1" => "2019",
"2" => "5",
"3" => "7",
"4" => "0",
);
$datetime_format = '';
foreach ($arr as $key => $value) {
if ($key == "4") {break;}
echo strlen($value);
if (strlen($value) >= 2) {
$datetime_format .= $value;
} elseif (strlen($value) == 2) {
$datetime_format .= $value;
} elseif (strlen($value) == 1) {
$datetime_format .= "0" . $value;
} else {
echo "Something is not right!";
}
if ($key <= "2") {$datetime_format .= '-';}
}
var_dump($datetime_format);
Output
string(10) "2019-05-07"
This question already has answers here:
Formatting DateTime object, respecting Locale::getDefault()
(6 answers)
Closed 5 years ago.
Im trying to get my date out of the DB in duth. Im spliting the date into seperate month, day and year variables and changed the month number to text but now i need to get in into dutch instead of english. I found some information on SO about it like setlocale(LC_ALL, 'nl_NL') but i cant get it to work.
<?php
include_once("db/db.php");
$statement = $db_con->prepare("select * from news_article where id > :id");
$statement->execute(array(':id' => 0));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
?>
<?php
foreach($list as $col)
{
// splitting into seperate month day year
$orderdate = explode('-', $col['datum']);
$year = $orderdate[0];
$month = $orderdate[1];
$day = $orderdate[2];
$dateObj = DateTime::createFromFormat('!m', $month);
$monthName =
$dateObj->format('F');
?>
//this needs to output in dutch
<p class="month"><?php echo $monthName ?></p>
<?php
$f = date('F');
function dutch_format($value) {
$months = array(
"January" => "januari",
"February" => "februari",
"March" => "maart",
"April" => "april",
"May" => "mei",
"June" => "juni",
"July" => "Juli",
"August" => "augustus",
"September" => "september",
"October" => "oktober",
"November" => "november",
"December" => "december"
);
return $months[$value];
}
echo $f;
echo "<br/>";
echo dutch_format($f);
?>
It will return DUTCH format. Guide me if I did any mistake
I have an object that stores the current date using Carbon as such:
class Events {
public $monthRange = 12;
public $today;
public function __construct() {
$this->today = Carbon::now();
}
}
I have a class that extends that class where I want to set a variable of $d = $this-today as such:
namespace Events;
use Carbon\Carbon;
class EventsData extends Events {
public $monthsNames = [
"1" => "January",
"2" => "February",
"3" => "March",
"4" => "April",
"5" => "May",
"6" => "June",
"7" => "July",
"8" => "August",
"9" => "September",
"10" => "October",
"11" => "November",
"12" => "December"
];
public function next_12_months() {
$next_12_months = [];
$d = $this->today;
array_push($next_12_months, $d->month);
for ( $i = 0; $i <= ($this->monthRange - 1); $i++ ) {
$d = $d->addMonths(1);
if ( $this->today != $d) {
array_push($next_12_months, $d->year);
}
var_dump($$this->today); //is being modified along with $d
var_dump($d);
$next_month = $d->month;
array_push($next_12_months, $next_month);
}
return $next_12_months;
}
}
The problem is that when i modified $d like this $d->addMonths(1), it seems $this->today also gets modified.
How do I prevent this from happening?
Clone the object
$d = clone $this->today;
More about cloning here.
been looking at this for a bit and now my eyes are crossed. :)
I have a calendar script that I found on snipplr.com It's pretty sweet. Props to the creators. Now, I have two things I want to customize.
Right now, the calendar spits out 12 months, January to December. And also the week ends on Sunday (grrrr). I am attempting to make it go from THIS MONTH, plus x number of months. For example, it would display December, plus 5 more months, so Dec, Jan, Feb, March, April, May.
I can tell in the code it uses a $i iteration to get through the months and display the appropriate dates. for($i=1;$i<=11;$i++)
SO, I tried changint it to this: for($i=$this_month;$i<=11;$i++)
$this_month of course being the date('m');
It does successfully display December, but no months after it. (Since it stops at 11). But if I up the 11 to another variable of $this_month+5, then the script doesnt know what months 13, 14 and 15 are.
Any help on this one? Here is the entire script I have thusfar.
function days_in_month($month, $year) {
if($month!=2) {
if($month==9||$month==4||$month==6||$month==11)
return 30;
else
return 31;
}
else
return $year%4==""&&$year%100!="" ? 29 : 28;
}
global $months;
$months = array(0 => 'January', 1 => 'February', 2 => 'March', 3 => 'April', 4 => 'May', 5 => 'June', 6 => 'July', 7 => 'August', 8 => 'September', 9 => 'October', 10 => 'November', 11 => 'December');
$days = array(0 => 'Monday', 1 => 'Tuesday', 2 => 'Wednesday', 3 => 'Thursday', 4 => 'Friday', 5 => 'Saturday', 6 => 'Sunday');
function render_calendar($this_year = null) {
if($this_year==null)
$this_month = date('m')-1;
$first = strtotime(date('m'));
$last = strtotime("+6 months", $this_month);
$this_year = date('Y');
$day_of_the_month = date('N', strtotime('1 January '.$this_year));
for($i=$this_month;$i<=12;$i++) {
// echo $i;
// if ($i==12) {
// $i = 0;
// }
echo $i;
echo "<table>
<caption>".$GLOBALS['months'][$i]."</caption>
<thead>
<tr>
<th>Sun</th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
</tr>
</thead>
<tbody>
<tr>";
for($n=1;$n<$day_of_the_month;$n++)
echo "<td></td>\n";
$days = days_in_month($i+1, $this_year);
$day = 0;
while($day<$days) {
if($day_of_the_month==8) {
echo ($day == 0 ? "" : "</tr>\n") . "<tr>\n";
$day_of_the_month = 1;
}
echo "<td style=\"border: 1px solid red;\">" . ($day+1) . "</td>\n";
$day_of_the_month++;
$day++;
}
echo "</tr>
</tbody>
</table>";
}
}
How about this for your loop:
for($i=$this_month;$i<=$this_month+5;$i++) {
// create a variable to hold the proper month index
$currentMonth = $i;
if ($i>11) {
$currentMonth -= 12;
}
// now replace all references to the $i index with $currentMonth
...
}
I'm sure there's a fairly easy way to do this. I have an the following data in an array:
Array
(
[ActivityDiaryEntry] => Array
(
[date] => 2011-03-03
[type] => Walking
[minutes] => 60
)
)
Array
(
[ActivityDiaryEntry] => Array
(
[date] => 2011-03-02
[type] => Walking
[minutes] => 22
)
)
Array
(
[ActivityDiaryEntry] => Array
(
[date] => 2011-03-01
[type] => Biking
[minutes] => 45
)
)
I'm not too skilled at PHP, but I know how to display this data by row to display as <tr><td>[date]</td><td>[type]</td><td>[minutes]</td></tr>. But I'd like to have the data display in columns like this:
2011-03-01 | 2011-03-02 | 2011-03-03
------------------------------------
Biking | Walking | Walking
------------------------------------
45 | 22 | 60
I didn't test this, but it should work. It should serve as an example of what needs to be done. I tried to write this to limit the number of foreach loops used. If I reordered the data first and then performed the takes, I'd of needed 4 foreach loops. The benefit to this method is that you don't need to update the code if more columns are added, so long as all records have the same number of columns.
<?php
// Your list of records
$records = array(
array( "key1" => "value", "key2" => "value", "key3" => "value" ),
array( "key1" => "value", "key2" => "value", "key3" => "value" ),
array( "key1" => "value", "key2" => "value", "key3" => "value" )
);
// Create an array to store the values of each row based on number of columns in first value
$rows = array_fill( 0, count( $records[0] ), "" );
$keys = array_keys( $records[0] );
// Create a column for each record in it's respective row.
foreach( $records as $k => $record )
for( $i=0, $max=count( $rows ); $i < $max; $i++ )
$rows[ $i ] .= "<td>".$record[ $keys[ $i ] ]."</td>";
// Turn each row in our array into an html table row.
print "<tr>".implode( "</tr><tr>", $rows )."</tr>";
Here's the code test: http://codepad.org/SSS8S2eU
A little ugly but works :')
$a[0] = array('ActivityDiaryEntry' => array("date" => "2011-03-03", "type"=> "Walking", "minutes" => 60));
$a[1] = array('ActivityDiaryEntry' => array("date" => "2011-03-03", "type"=> "Walking", "minutes" => 22));
$a[2] = array('ActivityDiaryEntry' => array("date" => "2011-03-03", "type"=> "Biking", "minutes" => 42));
$keys = array_keys($a[0]["ActivityDiaryEntry"]);
echo '<table>';
for($c = 0; $c < count($a); $c++) {
echo '<tr>';
for($i = 0; $i < count($a[$c]['ActivityDiaryEntry']); $i++) {
echo '<td>' . $a[$i]['ActivityDiaryEntry'][$keys[$c]] . '</td>';
}
echo '</tr>';
}
echo '</table>';
http://codepad.org/5Tuk8x3Q
This code works if i am not wrong defining the array, but i suggest you play with all the options provided here and find a better solution.
$data = array (
array (
'ActivityDiaryEntry' => array
(
'date' => "2011-03-03",
'type' => "Walking",
'minutes' => 60
)
),
array (
'ActivityDiaryEntry' => array
(
'date' => "2011-03-02",
'type' => Walking,
'minutes' => 22
) ),
array (
'ActivityDiaryEntry' => array
(
'date' => "2011-03-01",
'type' => Biking,
'minutes' => 45
)
)
);
echo "<table>";
$i = 0;
foreach ($data as $key => $val) {
echo "<tr>";
foreach ($data as $kk => $vv){
if ($i==0) {
echo "<td>". $vv['ActivityDiaryEntry']['date'] ."</td>";
}else if ($i == 1){
echo "<td>". $vv['ActivityDiaryEntry']['type'] ."</td>";
}else if ($i == 2){
echo "<td>". $vv['ActivityDiaryEntry']['minutes'] ."</td>";
}
}
echo "</tr>";
$i++;
}
echo "</table>";
This would be a great candidate for DataTables, which is actually Javascript that I use to display my results generated on the back end by PHP. It's a full-blown javascript grid system that adds a ton of features to standard HTML table outputs. To make it work you would:
Get your results as shown and output as a json_encoded string (i.e, echo json_encode($array) I do this in a separate file so it outputs clean text to the screen.
On the page to display the table, setup a "dummy table"
Setup Datatables in the same page as the dummy table like this:
$(document).ready(function() {
$('#replace').dataTable( {
"bProcessing": true,
"sAjaxSource": 'file.php'
} );
} );
Set values for sorting, filtering, paging, etc. per the tutorial.
Datatables gives you so much more power than just a standard HTML table, and you're already 90% of the way there with the data. It's so much more user friendly than just jamming stuff on the screen.
Before transposing your data (converting columns to rows), you must reduce the depth/complexity by removing the unusable first level and generate an indexed array of what is left.
Then iterate the first array in the new, simplified data structure and extract column data. Each column (there are three) will be displayed in its own table row using a flexible implode()ing technique.
Code: (Demo)
$subarrays = array_column($array, "ActivityDiaryEntry");
echo '<table>';
foreach ($subarrays[0] as $column => $notUsed) {
echo '<tr><td>' , implode('</td><td>', array_column($subarrays, $column)) , '</td></tr>';
}
echo '</table>';
Output:
<table>
<tr>
<td>2011-03-03</td>
<td>2011-03-03</td>
<td>2011-03-03</td>
</tr>
<tr>
<td>Walking</td>
<td>Walking</td>
<td>Biking</td>
</tr>
<tr>
<td>60</td>
<td>22</td>
<td>42</td>
</tr>
</table>
You could write a for loop for each field, displaying one row in each loop.
The Javascript answer below might be a good way to do it, but I would suggest using PHP and tables if you are not completely comfortable using Javascript in your applications. It is also good PHP practice.
If I were you, I'd use code like this, and css properties to format the table how you'd like.
echo '<table>';
echo '<tr><td>Date</td><td>Type</td><td>Minutes</td></tr>';
foreach ($array as $entry){
echo '<tr>';
echo '<td>'.$entry['date'].'</td>';
echo '<td>'.$entry['type'].'</td>';
echo '<td>'.$entry['minutes'].'</td>';
echo '</tr>';
}
echo '</table>';
You can use stuff like this to edit your tables display, also check out http://www.w3schools.com/css/css_table.asp
echo '<tr style="border-bottom: 1px solid black;"></tr>';
cheers