Reputation: 399
I'm using Codeigniter 3 (calendar class) and I have this function to get calendar data (the table just has a date column and a data column):
function get_calendar_data($year, $month) {
$query = $this->db->select('date, data')->from('calendar')->like('date', "$year-$month", 'after')->get();
$cal_data = array();
foreach ($query->result() as $row) {
$cal_data[substr($row->date,8,2)] = $row->data;
}
return $cal_data;
}
It works OK and produces an array for a month, $cal_data, consisting of days as the keys and values (in this case the names of colors) and var_dump typically looks like this:
array (size=6)
26 => string 'amber' (length=5)
27 => string 'red' (length=3)
28 => string 'red' (length=3)
25 => string 'amber' (length=5)
'04' => string 'red' (length=3)
'07' => string 'red' (length=3)
which the calendar requires. However, there is a problem with days that have leading zeros as the calendar appears to need them without. So the values do not show for 04 and 07. As a test, I rewrote the foreach loop to say:
$cal_data[substr($row->date,9,1)] = $row->data;
so the key would pick up only the final character of the date string, and in that case the values for 4 and 7 did indeed show correctly.
Is there a simple way to remove the leading zeros so the keys would be 4 and 7?
Upvotes: 2
Views: 484
Reputation: 23968
I'm guessing since you have substr(..., 8, 2) I assume it's a full date like 2017-07-30 or something like it.
So that means you can use date() to manipulate the data.
$cal_data[date("j", $row->date)] = $row->data;
Date("j") is day number without leading zeros.
http://php.net/manual/en/function.date.php
Upvotes: 2
Reputation: 587
You can do this (note the cast to int):
foreach ($query->result() as $row) {
$cal_data[(int)substr($row->date,8,2)] = $row->data;
}
Upvotes: 5