我有一个txt文件,我读出来显示日历事件 php文件的结构形式为:
<?php
$file = fopen("admin/events/events.txt", "r");
while(!feof($file)){
$line = fgets($file);
$result=htmlentities($line);
$s = $result;
preg_match_all('/data-day=\'([^\']*)\'/', $s, $matches);
foreach($matches[1] as $idx => $datevalue)
{
$year = substr($datevalue, 0, 4);
$month = substr($datevalue, 4, 2);
$day = substr($datevalue, 6, 2);
}
$line = trim($line);
if ($line != "") {
$line = str_replace("<div data-role='day' data-day='$year$month$day", "<b><u>Datum:</b></u> $day-$month-$year ", $line);
$line = str_replace("'><div data-role='event' data-name='<h6>", " <br><b><u>Event:</b></u> ", $line);
$line = str_replace("' data-start='", " <br><b><u>Start:</b></u> ", $line);
$line = str_replace("' data-end='", " <br><b><u>Einde:</b></u> Tot ", $line);
$line = str_replace("' data-location='", " <br><b><u>Locatie:</b></u> ", $line);
$line = str_replace("</h6>", " <br><b><u>Inhoud event:</b></u><br> ", $line);
$line = str_replace("'></div></div>", "", $line);
echo "<div class='event'>$line</div>";
}
}
fclose($file);
?>
获取读取内容的txt文件是
<div data-role='day' data-day='20131202'><div data-role='event' data-name='<h6>event</h6>eventtext' data-start=00.00 ' data-end='9.00' data-location='at home'></div></div>
<div data-role='day' data-day='20140102'><div data-role='event' data-name='<h6>event</h6>eventtext' data-start=00.00 ' data-end='9.00' data-location='at home'></div></div>
<div data-role='day' data-day='20140522'><div data-role='event' data-name='<h6>event</h6>eventtext' data-start=00.00 ' data-end='9.00' data-location='at home'></div></div>
当数据日读出时,是否可以对php文件中的事件进行排序?
答案 0 :(得分:1)
您可以创建一个多维数组:第一个元素是日期数组,第二个元素是行数组。然后用array_multisort
排序,所以代码是:
<?php
$file = fopen("events.txt", "r");
$out_arr=array('sort'=>array(), 'data'=>array());
while(!feof($file)){
$line = fgets($file);
$result=htmlentities($line);
$s = $result;
preg_match_all('/data-day=\'([^\']*)\'/', $s, $matches);
foreach($matches[1] as $idx => $datevalue)
{
$year = substr($datevalue, 0, 4);
$month = substr($datevalue, 4, 2);
$day = substr($datevalue, 6, 2);
}
$line = trim($line);
if ($line != "") {
$out_arr['sort'][] = mktime(0,0,0,$month, $day,$year);
$line = str_replace("<div data-role='day' data-day='$year$month$day", "<b><u>Datum:</b></u> $day-$month-$year ", $line);
$line = str_replace("'><div data-role='event' data-name='<h6>", " <br><b><u>Event:</b></u> ", $line);
$line = str_replace("' data-start='", " <br><b><u>Start:</b></u> ", $line);
$line = str_replace("' data-end='", " <br><b><u>Einde:</b></u> Tot ", $line);
$line = str_replace("' data-location='", " <br><b><u>Locatie:</b></u> ", $line);
$line = str_replace("</h6>", " <br><b><u>Inhoud event:</b></u><br> ", $line);
$line = str_replace("'></div></div>", "", $line);
$out_arr['data'][] = "<div class='event'>$line</div>";
}
}
array_multisort($out_arr['sort'], SORT_ASC, SORT_NUMERIC, $out_arr['data']);
echo join('', $out_arr['data']);
fclose($file);
?>