Я хотел бы иметь возможность выводить временную шкалу, содержащую количество недель из серии дат, содержащихся в таблице. Например, предположим, у меня есть даты 12/9/10 (четверг), 13.12.10 (понедельник), 15/12/10 (среда) и 21.12.10 (вторник), каждое в записи в таблице MySQL.
То, что я хотел бы вывести - это то, что рассчитывает количество недель на основе этих дат, например:
Неделя 1: 12.09.10
Неделя 2: 13.12.10, 15.12.10
Неделя 3: 12/21/10
Я знаю, как получить номер недели в данном году (как, например, сегодня мы на неделе 49), но, поскольку у меня может быть ЛЮБОЙ диапазон дат, я вычисляю недели, а не неделю года.
Я мог бы просто преобразовать недели года в счетчик и отобразить их последовательно (если даты начинаются на неделе 49 и продолжаются до недели 52, недели 49 = 1, недели 50 = 2 и т. Д.), Но если у меня есть даты, которые охватывают более 2 лет (например, с 12/25/10 по 1/2/11), это проблематично.
Любая помощь будет принята с благодарностью! Мне не нужен код MySQL - просто преобразование строки даты. Я крутил свои колеса на этом!
ОБНОВЛЕНИЕ: Просто подумал, что поделюсь кодом, который наконец решил эту проблему. Это не мое окончательное решение, так как данные все еще нужно обрабатывать, но я получил то, что хотел, и теперь я могу работать с этими данными. Спасибо всем, кто оставил ответ.
<?php
header("Content-type: text/html; charset=utf-8");
require_once('includes/connections/know_db.php');
?>
<?php
//First let's get all the years any given project will span...
mysql_select_db($database_know_db, $know_db);
$query_GetYears = sprintf("SELECT DISTINCT(YEAR(target_date)) as project_years FROM project_items WHERE projects_id = 136 AND target_date IS NOT NULL ORDER BY project_years ASC");
$GetYears = mysql_query($query_GetYears, $know_db) or die(mysql_error());
//A function allowing us to extract the week of the year from the next query, and then convert its value into an integer.
function ConvertToWeek($target_date) {
$week = date('W', strtotime($target_date));
$week_int = intval($week);
return $week_int;
}
//Now let's loop through our years, and get project item data (via MySQL) for each...
while ($row_GetYears = mysql_fetch_assoc($GetYears)) {
echo $row_GetYears['project_years']."<br />";
mysql_select_db($database_know_db, $know_db);
$query_GetItems = sprintf("SELECT DISTINCT(target_date) FROM project_items WHERE projects_id = 136 AND target_date IS NOT NULL AND YEAR(target_date) = '".$row_GetYears['project_years']."' ORDER BY target_date ASC");
$GetItems = mysql_query($query_GetItems, $know_db) or die(mysql_error());
//Loop through the results of our project items, convert them to week numbers from our function, then toss them into an array.
while ($row_GetItems = mysql_fetch_assoc($GetItems)) {
$weeks[] = ConvertToWeek($row_GetItems['target_date']);
//Array_unique essentially removes duplicate numbers...
$result = array_unique($weeks);
}
// get the first value in the $weeks array, then to be safe, convert its value to an integer.
$start_week = array_shift(array_values($weeks));
$start_week_no = intval($start_week);
// get the last value in the $weeks array (will use this later to find differences in weeks between overlapping years).
$end_week = array_pop(array_values($weeks));
echo 'Start week: '.$start_week_no."<br />";
echo 'End week: '.$end_week."<br />";
//Output our weeks for the purposes of display.
foreach ($result as $week_count) {
echo ltrim($week_count, "0").'<br />';
}
/*Now let's find the weeks in the sequence where weeks are not represented (missing).
By doing this, we can get a number of for each week we don't have where datasets will be empty.
*/
// construct a new array:1,2....max(given array).
$result2 = range($start_week_no,max($result));
// use array_diff to get the missing weeks
$missing = array_diff($result2,$result);
//Output our missing weeks for the purposes of display.
foreach ($missing as $missing_weeks) {
echo $missing_weeks.' (missing)<br />';
}
/*
Before we close our original while loop--the one that loops through each year, we need to unset our arrays so they are empty upon
each new loop.
*/
unset($weeks);
unset($result);
//End our original while loop.
}
?>