title: PHP sorting object array by certain criteria?
body: <p>I have something like this: </p>
  
  <pre><code>$i = 0;
  
  foreach($tracks['results'] as $track){
      $trackName[$i] = $track['name'];
      $trackPlaycount[$track['name']] = $track['playcount'];
      $trackPercent[$track['name']] = $track['percent'];
      $i++;
  }
  
  $this-&gt;trackName = $trackName;
  $this-&gt;trackPlaycount = $trackPlaycount;
  $this-&gt;trackPercent = $trackPercent;
  </code></pre>
  
  <p>how could I sort these objects by playcount? From what I have read so far I understand I should probably create a compare function and then make it work with usort(), right? But I'm not quite sure how to accomplish that...</p>
  
  <p>thank you</p>
  
  <p><br /><br /><br />
  <strong>edit:</strong> ok, so now I've got it like this:</p>
  
  <pre><code>public function firstmethod(){
      // there are some more parameters here of course
      // but they worked before, not important for the problem
      $i = 0;
      foreach($tracks['results'] as $track){
          $trackName[$i] = $track['name'];
          $trackPlaycount[$track['name']] = $track['playcount'];
          $trackPercent[$track['name']] = $track['percent'];
          // this part is new
          $tracksArray[$i] = array(
              'name' =&gt; $trackName[$i], 
              'playcount' =&gt; $trackPlaycount[$track['name']], 
              'percentage' =&gt; $trackPercent[$track['name']]
          );
          $i++;
      }
  
      usort($tracksArray, array($this, 'sortByCount'));
  
      $i = 0;
      // this is to put the new sorted array into the old variables? 
      foreach($tracksArray as $temp){
          $trackName[$i] = $temp['name'];
          $trackPlaycount[$trackName[$i]] = $temp['playcount'];
          $trackPercent[$trackName[$i]] = $temp['percentage'];
          $i++;
      }
  
      $this-&gt;trackName = $trackName;
      $this-&gt;trackPlaycount = $trackPlaycount;
      $this-&gt;trackPercent = $trackPercent;
  }
  
  
  public function sortByCount($a, $b){
      if($a["playcount"] == $b["playcount"]) {
          return 0;
      }
      return ($a["playcount"] &lt; $b["playcount"]) ? -1 : 1;
  }   
  </code></pre>
  
  <p>this now works... 
  thank you everyone</p>