Re: Re: how to sort by value in associative array
| From: | Chris Adams | Date: | Sun, 07 Apr 2002 22:55:04 +0000 |
| Subject: | Re: Re: how to sort by value in associative array | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-91959@lists.php.net to get a copy of this message | ||
On Sat, 6 Apr 2002 18:21:10 -0600, Peter J. Schoenster
<peter@schoenster.com> wrote:
> I tried the above.
>
> uksort ($ArrayOfNewsLinks, "SortByValue");
>
> function SortByValue ($a, $b) {
> if ($a["language"] == $b["language"]) return 0;
> return ($a["language"] > $b["language"]) ? 1 : -1;
> }
>
>
> or this
>
> function SortByValue ($a, $b) {
> return strcmp ( $a["language"], $b["language"]);
> }
>
> Doesn't work.
I should have caught this earlier. Try uasort() - uksort() sorts on the
array *key*, not the value.
<?
$ArrayOfNewsLinks = array(
"http://dailynews.yahoo.com/fc/World/Brazil/"
=> array(
'title' => 'Yahoo Brazil News',
'category' => 'news',
'language' => 'English',
),
"http://news.bbc.co.uk/hi/english/world/americas/default.stm"
=> array(
'title' => 'BBC News',
'category' => 'news',
'language' => 'English',
),
"http://news.yahoo.com/" => array(
'title' => 'Yahoo News',
'category' => 'news',
'language' => 'English',
),
"http://chinese.news.yahoo.com/"
=> array(
'title' => 'Yahoo News',
'category' => 'news',
'language' => 'Chinese',
)
);
function news_sort($a, $b) {
// Two key sort: first by language, then by title
$i = strcmp($a['language'], $b['language']);
if ($i != 0) {
return $i;
} else {
return strcmp($a['title'], $b['title']);
}
}
header("Content-Type: text/plain");
print_r($ArrayOfNewsLinks);
uasort($ArrayOfNewsLinks, "news_sort");
print_r($ArrayOfNewsLinks);
?>