-1

请您帮忙,我有以下$events数组,我想按 sort 的值对我的 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']
    }
 }
4

2 回答 2

2

似乎您想对每个事件中的猫数组进行排序。在这种情况下,将排序函数移动到嵌套循环内:

foreach($events as $event) {
    usort($event['cats'], function ($a, $b) {
        return $a['sort'] - $b['sort'];
    });
    foreach($event['cats'] as $cat) {
        echo $cat['name']
    }
}
于 2013-01-31T10:33:07.527 回答
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

活生生的例子

于 2013-01-31T10:42:10.140 回答