PHP排序问题

标签 php sorting csv

我想请求你的帮助。 我有一个 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/

相关文章:

php - 如何获取点击时的值(循环值)?

php - 一种将数组及其键保存到数据库的有效方法

bash - 如何反转文本 block 的顺序

python - csv DictReader 上的 "Doing work"失败

file-upload - 当上传大于 POST_MAX_SIZE 时,PHP $_POST/$_FILES 为空

php - 显示标签与页面标题匹配的帖子

PHP 基于子对象值的短数组

用于对两个字段进行排序的 Ruby 习惯用法

csv - 从 csv 导入文件创建 Neo4j 关系

javascript - 如何使用 javascript 计算 *.CSV 文件中每行的值数?