不正确使用usort

时间:2013-01-31 10:22:38

标签: php sorting usort

请帮助,我有以下 $ events 数组,我想在我的events数组中按< cat '数组排序排序

Array ( [0] => Array ( 
          [date] => 20130329 
          [title] => Run 
          [cats] => Array ( 
           [0] => Array ( 
             [name] => Cause 2
             [slug] => cause-2
             [sort] => 1) ) 
          )

        [1] => Array ( 
          [date] => 20130131
          [title] => Run2 
          [cats] => Array ( 
           [0] => Array ( 
            [name] => Abused Children 
            [slug] => abused-children 
            [sort] => 2 ) 
           [1] => Array ( 
            [name] => Animal Welfare 
            [slug] => animal-welfare
            [sort] => 3 ) 
           [2] => Array ( 
            [name] => Education 
            [slug] => education 
            [sort] => 1 ) 
            )  )

当我在[cat]上做foreach时,我希望它按排序顺序进行迭代,例如。

Event: Run2
 Cat: Education
 Cat: Abused Children
 Cat: Animal Welfare

在我的代码中,我有类似的东西

 usort($events, function($a, $b) {
 return $a['cats']['sort'] - $b['cats']['sort']; });

 foreach($events as $event) {
    foreach($event['cats'] as $cat) {
      echo $cat['name']
    }
 }

2 个答案:

答案 0 :(得分:2)

好像你想在每个事件中对cats数组进行排序。在这种情况下,在嵌套循环中移动sort函数:

foreach($events as $event) {
    usort($event['cats'], function ($a, $b) {
        return $a['sort'] - $b['sort'];
    });
    foreach($event['cats'] as $cat) {
        echo $cat['name']
    }
}

答案 1 :(得分:1)

好吧,发表评论时我有点累。所以这是一个解决方案,在输出之前将源数组调整到您想要的顺序。

$events=array(array("date"=>"20130329","title"=>"Run","cats"=>array(array("name"=>"Cause 2","slug"=>"cause-2","sort"=>1))),array("date"=>"20130131","title"=>"Run2","cats"=>array(array("name"=>"Abused Children","slug"=>"abused-children","sort"=>2),array("name"=>"Animal Welfare","slug"=>"animal-welfare","sort"=>3),array("name"=>"Education","slug"=>"education","sort"=>1))));
$events=array_map(function($arr){
    usort($arr["cats"],function($a,$b){
        return $a["sort"]-$b["sort"];
    });
    return $arr;
},$events);
foreach($events as $event)
{
    echo "Event: ".$event["title"]."\n";
    foreach($event["cats"] as $cat)
    {
        echo "  Cat: ".$cat["name"]."\n";
    }
}

以上输出:

Event: Run
  Cat: Cause 2
Event: Run2
  Cat: Education
  Cat: Abused Children
  Cat: Animal Welfare

Live example