drza10046 2014-06-21 19:55
浏览 183
已采纳

使用usort(PHP)对数组中的2个字段ASC进行排序

i have a textfile with this content (id;date;user):

8559;2014-06-13;Carlos
8584;2014-06-23;1A Auto
8398;2014-06-02;LRDream
7738;2014-05-19;Felicitia Motors
8475;2014-06-06;Motori
8331;2014-06-30;Otto Burner
8521;2014-06-24;Mirage
3699;2014-06-30;LR DMJ
8050;2014-05-19;1A Auto
7428;2014-05-20;Carlos

Goal is to output this data sorted by 1) month and 2) username.

<?

$data = file("data.csv");

foreach ($data as $value)
{
$bla=explode(";",$value);
$new[$bla[0]]['date']=substr($bla[1],0,-3);
$new[$bla[0]]['user']=$bla[2];
}

function comp($a, $b)
{ if ($a['date'] == $b['date']) { return $a['user'] - $b['user']; }
return strcmp($a['date'], $b['date']);
} 
usort($new, 'comp');

foreach ($new as $value)
{
echo $value['date']." - ".$value['user']."<br>";
}

?>

This sorts the months correctly but the users are not really sorted:

2014-05 - Carlos
2014-05 - Felicitia Motors
2014-05 - 1A Auto <---
2014-06 - LR DMJ
2014-06 - Mirage
2014-06 - Motori
2014-06 - LRDream <---
2014-06 - Carlos <---
2014-06 - Otto Burner
2014-06 - 1A Auto <---

What wrong with the code?

Thanks! NBG

  • 写回答

1条回答 默认 最新

  • dougong9987 2014-06-21 19:59
    关注

    That's because you are not comparing the usernames -- you are subtracting them numerically, which gives totally inappropriate results (see string conversion to numbers).

    Replace return $a['user'] - $b['user'] with return strcmp($a['user'], $b['user']) to get the expected result.

    Shameless self-promotion: You could also consider using the handy sorting technique I give here to get the correct result with much more appealing code:

    usort($new, make_comparer('date', 'user'));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示