-1

I have the following JSON:

    [{
      "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"
   }]

And here's my code to decode that JSON and put it into a PHP array:

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

My question is, if I add in a $testimonial->sort_order= $row['sort_order']; can I use that to sort the $testimonial array? And is there a way to sort it before the foreach loop?

Naguib Ihab
  • 4,259
  • 7
  • 44
  • 80

1 Answers1

0

Use usort:

usort($testimonials_table_json, function ($a, $b) {
  return $b['sort_order'] - $a['sort_order'];
});
vp_arth
  • 14,461
  • 4
  • 37
  • 66