2016-06-18 10 views
-1

ich die folgende JSON haben:nach einem PHP-Array-Sortierung auf eine bestimmte Spalte

[{ 
     "id":"1", 
     "testimony":"I recently went to Perceptive Mind on behalf of a client to get assistance in the web-development of an online invoicing system.\n\t\t\t\t\t\t\t\t\t\t\t\t\tThe work they did for me was done quickly and with great care. What I found most notable about Perceptive Mind was that it worked with my budget, I didn't feel overcharged and had plenty of tech support and communication throughout the project.\n\t\t\t\t\t\t\t\t\t\t\t\t\tI will definitely be using Perceptive Mind in the future!", 
     "author":"Miles Hellyer", 
     "title":"Founder", 
     "company":"Chalk Marketing", 
     "sort_order":"200" 
    }, 
    { 
     "id":"2", 
     "testimony":"Just like to thank Nick for\r\n\t\t\t\t\t\t\t\t\t\t\t\t\this outstanding and professional work, he has created a great website\r\n\t\t\t\t\t\t\t\t\t\t\t\t\twhich suits our needs. He was efficient, helpful and very\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tfriendly! Definitely would recommend using his services", 
     "author":"Jennifer Mouhaweg", 
     "title":"Manager", 
     "company":"The Lockout Guys", 
     "sort_order":"400" 
    }] 

Und hier ist mein Code, dass JSON zu entschlüsseln und sie in eine PHP-Array setzen:

$testimonials_array; 
     $testimonials_table_json = json_decode(file_get_contents('../app/database/testimonials.JSON'),true); 
     foreach($testimonials_table_json as $row) { 
      $testimonial = $this->model('TestimonialModel'); 
      $testimonial->testimony = $row['testimony']; 
      $testimonial->author = $row['author']; 
      $testimonial->title = $row['title']; 
      $testimonial->company = $row['company']; 

      $testimonials_array[] = $testimonial; 
     } 

     return $testimonials_array; 

Meine Frage ist, wenn ich in $testimonial->sort_order= $row['sort_order']; hinzufügen kann ich das verwenden, um das $testimonial Array zu sortieren? Und gibt es eine Möglichkeit, es vor der foreach Schleife zu sortieren?

+0

Haben Sie versucht, [diese] (http://stackoverflow.com/a/4022355/5447994)? – Thamilan

Antwort

0

Verwendung usort:

usort($testimonials_table_json, function ($a, $b) { 
    return $b['sort_order'] - $a['sort_order']; 
}); 
+0

Das hat funktioniert, danke. –

Verwandte Themen