1

Possible Duplicate:
How to sort arrays inside an array?

Probably this is easily accomplished by a native php function, however I can't seem to find it in the manual. I have something like the following array:

[0] (Array)#3
        [date_published] "2011-10-10 21:25:56"
        [domain] "gawker.com"
        [domain_rank] "909"
        [language] "en"
        [publisher] ""MAIN" via Steve in Google Reader"
        [title] "Genetically-modified salmon are closer than ever to a dinner plate near you [Genetic Engineering]"
        [url] "http://feeds.gawker.com/~r/io9/full/~3/s_6bCNerlW0/genetically+modified-salmon-are-closer-than-ever-to-a-dinner-plate-near-you"
      [1] (Array)#4
        [date_published] "2011-10-10 21:06:00"
        [domain] "huffingtonpost.com"
        [domain_rank] "85"
        [publisher] "PoliticsPolitics | Politics"
        [title] "John Geyman: Health Care: A Casualty of Class Warfare"
        [url] "http://feeds.huffingtonpost.com/~r/HP/Politics/~3/ZsqVSZMcWKM/health-care-statistics-america_b_990263.html"

And I am looking to order it by domain_rank, how could i acccomplish this through PHP?

Community
  • 1
  • 1
Osvaldo Mercado
  • 950
  • 3
  • 13
  • 24

3 Answers3

4
<?php
$array = array(
    array('domain_rank' => 909, 'a'), 
    array('domain_rank' => 100, 'b'),
    array('domain_rank' => 500, 'c'),
    array('domain_rank' => 100, 'd')
);
// since php 5.3
usort($array, function ($a, $b) {
    return $a['domain_rank'] > $b['domain_rank'];
});
// below php 5.3
function sortByDomainRank($a, $b) {
    return $a['domain_rank'] > $b['domain_rank'];
}
usort($array, 'sortByDomainRank');


print_r($array);
?>

cf. http://php.net/manual/en/function.usort.php which allows you to give a callback function for sorting.

TimWolla
  • 28,958
  • 8
  • 59
  • 84
0

This is a way, not the best.

function subval_sort($a,$subkey) {
    foreach($a as $k=>$v) {
        $b[$k] = strtolower($v[$subkey]);
    }
    asort($b);
    foreach($b as $key=>$val) {
        $c[] = $a[$key];
    }
    return $c;
}

$data = subval_sort($data,'domain_rank'); 

Also you could use Usort like so:

function compare($a, $b) {
    return ($a['domain_rank'] < $b['domain_rank']);
}

usort($data, 'compare');
Wesley
  • 2,152
  • 16
  • 26
-2

There are several php functions to handle this depending on your exact needs. Look at the php manual as it is your friend. Best friend even.

http://www.php.net/manual/en/array.sorting.php

fraklo
  • 61
  • 2
  • 8