Solved

Sort Associative PHP Array on value but maintain key order

Posted on 2008-10-28
6
462 Views
Last Modified: 2012-05-05
Hi,

Trying to sort an array

e.g.

array
(
 [apple] => 2
 [banana] => 1
 [goat]=>1
 [dog]=>2
)

sort on the numbers but keep key order

after sort

array
(
 [banana] => 1
 [goat]=>1
 [apple] => 2
 [dog]=>2
)

Thanks!!

0
Comment
Question by:BrentNJ
6 Comments
 
LVL 15

Expert Comment

by:MMDeveloper
ID: 22825097
try asort()
0
 

Author Comment

by:BrentNJ
ID: 22825683
Tried that already. It didn't maintain the order of the fruit name but did do the numeric correctly
0
 
LVL 27

Expert Comment

by:ddrudik
ID: 22826258
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 27

Accepted Solution

by:
ddrudik earned 100 total points
ID: 22826274
Seems there was a typo on that function, see this revision:
http://us.php.net/manual/en/function.asort.php#80802
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 22830376
I think you may want this.  The man page for asort refers to the man page for sort for the sort flags.

HTH, ~Ray
<?php 
 
$sorted_array = asort($array, 'SORT_NUMERIC');

Open in new window

0
 
LVL 27

Expert Comment

by:ddrudik
ID: 23038771
Thanks for the question and the points.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to dynamically set the form action using jQuery.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question