我想请求你的帮助。 我有一个 CSV 文件,其中存储了 4 个不同类别的值。 ( A B C D ) 我按日期顺序显示这些值,但是,我希望我的页面按类别显示它们,然后按日期对它们进行排序。
$_news_date 是存储日期的位置,$news_category 是存储类别的位置。
For example: I'd want category A to be the first and B to be the secound, C the third, etc. Than, if I'd have 2 items as A, I'd want those to be in order by date, so the most recent would be on the top of the list. This would mean that a category A item would be above a category B item, even if it's older.
if (!count($news_headlines)>0){
echo 'Nothing to display for the moment. ';
}else{
foreach ($news_headlines as $key => $item){
list($news_id,$news_date,$news_title,$news_body,$news_category) = $item;
$formatted_date = date('d.m.y',$news_date);
if($news_category == 'A') {
$color = '#FF0000';
$weight = 'bold';
}
else if($news_category == 'B') {
$color = '#FF9900';
$weight = 'normal';
}
else if($news_category == 'C') {
$color = '#000000';
$weight = 'normal';
}
else {
$color = '#33CC33';
$weight = 'normal';
}
echo '<h2><p style="color: '.$color.'; font-weight: '.$weight.';">'.$formatted_date.' - '.$news_category.' - '.$news_title.'</p></h2>';
最佳答案
首先你需要创建一个数组然后排序.. 尝试这样的事情
if (!count($news_headlines)>0)
{
echo 'Nothing to display for the moment. ';
}
else{
$req_array = array();
foreach ($news_headlines as $key => $item)
{
list($news_id,$news_date,$news_title,$news_body,$news_category) = $item;
$formatted_date = date('d.m.y',$news_date);
$req_array[]['id'] = $news_id;
$req_array[sizeOf($req_array)-1]['date'] = formatted_date;
$req_array[sizeOf($req_array)-1]['title'] = $news_tile;
// similarly add othe values to this array
}
foreach($req_array as $key=>$value)
{
$category[] = $value['category'];
$date[] = $value['date'];
}
$req_array = array_multisort($category,SORT_ASC,$date,SORT_DESC,$req_array);
----
// rest code
现在 $req_array
应该包含所需的数组..
关于PHP排序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15742802/