-1

よろしくお願いします。次の$events配列があり、events配列内の' cat '配列をsortの値で並べ替えたいと思います。

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 に答える