0

Possible Duplicate:
Sort array of objects
sort an object array in php

EDIT: This is a duplicate question. Just close this

I have an array of objects stored into $articles, and they don't necessarily come back in any particular order. I'm trying to sort the objects based on the idarticles. I know how to do this in javascript, but no idea how to do it in PHP. Here is a sample response. I echo'd it out with json_encode for readability. Any help would be great

[
   {
      "idarticles":"61",
      "full_text":"",
      "main_image":"",
      "tags":null,
      "url":null,
      "summary":null,
      "title":"No Title Given"
   },
   {
      "idarticles":"64",
      "full_text":"",
      "main_image":"http:\/\/i2.cdn.turner.com\/cnn\/dam\/assets\/121014085050-11-stratos-1014-horizontal-gallery.jpg",
      "tags":"Sound,New Mexico,Maxima and minima",
      "url":"some string",
      "summary":"text",
      "title":"text"
   },
   {
      "idarticles":"63",
      "full_text":"",
      "main_image":"http:\/\/i2.cdn.turner.com\/cnn\/dam\/assets\/121014085050-11-stratos-1014-horizontal-gallery.jpg",
      "tags":"Sound,New Mexico,Maxima and minima",
      "url":"some string",
      "summary":"text",
      "title":"text"
   }
]
Community
  • 1
  • 1
Bill
  • 5,478
  • 17
  • 62
  • 95

3 Answers3

1

It's easy - use uasort function (which is user-defined sorting):

uasort($yourData, function ($a, $b) {
    if ($a['idarticles'] == $b['idarticles']) {
        return 0;
    }
    return ($a['idarticles'] < $b['idarticles']) ? -1 : 1;
});

The comparison function is pretty standard here (see examples here) - only it sorts not by values themselves, but by certain keys in your data.

NikitaBaksalyar
  • 2,414
  • 1
  • 24
  • 27
0

Try using usort:

function sortByArticleId($a,$b){
  return strcmp($a->idarticles,$b->idarticles);
}

usort($ary,'sortByArticleId');
Brad Christie
  • 100,477
  • 16
  • 156
  • 200
0

You can simply do

usort($list, function ($a, $b) {
    $a = $a['idarticles'];
    $b = $b['idarticles'];
    return ($a == $b) ? 0 : (($a < $b) ? -1 : 1);
});
Baba
  • 94,024
  • 28
  • 166
  • 217