Question

Please can you kindly assist, I have the following $events array and I want to sort the 'cat' array within my events array by the value of the 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 ) 
            )  )

When I do a foreach on the [cat], I want it to iterate by the sort order, eg.

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

In my code I have something like this

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

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

Solution

Seems like you want to sort the cats array inside each event. In that case, move the sort function inside the nested loop:

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

OTHER TIPS

Alright, I was a little tired when I post my comment. So here's a solution, tempering your source array into your desired order before output.

$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";
    }
}

The above outputs:

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

Live example

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top