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"
   }
]
3
  • Yea, got it... it was basically a duplicate. Commented Oct 18, 2012 at 2:18
  • @Bill you can easily delete ... Commented Oct 18, 2012 at 2:21
  • @baba it won't let me delete... too many answers already Commented Oct 20, 2012 at 1:11

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Try using usort:

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

usort($ary,'sortByArticleId');

Comments

0

You can simply do

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.