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

使用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

我有一个包含此内容的文本文件(id; date; user): p> 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 \ n7428; 2014-05-20; Carlos code> pre>

目标是输出按1)月和2)用户名排序的数据。 p>

 &lt;?
 
 $ data = file(“data.csv”); 
 
foreach($ data as $ value)
 {
 $ bla = explode(“;”,  $值); 
 $的新[$ BLA [0]] [ '日期'] = SUBSTR($ BLA [1],0,-3); 
 $的新[$ BLA [0] [ '用户'  ] = $ bla [2]; 
} 
 
函数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']。“&lt; br&gt;”; 
} 
 
?&gt; 
  code>  pre> \  n 
 

这正确地对月份进行了排序,但用户并没有真正排序: p>

  2014-05  -  Carlos 
2014-05  -  Felicitia Motors 
2014-05  -  1A Auto&lt; --- 
2014-06  -  LR DMJ 
2014-06  -  Mirage 
2014-06  -  Motori 
2014-06  -  LRDream&lt; --- 
2014-06  -  Carlos&lt; --- 
201414  -06  -  Otto Burner 
2014-06  -  1A Auto&lt; --- 
  code>  pre> 
 
 

代码有什么问题? p>

谢谢! NBG p> div>

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'));