Solved

Sort Associative PHP Array on value but maintain key order

Posted on 2008-10-28
6
468 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
WordPress Tutorial 1: Installation & Setup

WordPress is a very popular option for running your web site and can be used to get your content online quickly for the world to see. This guide will walk you through installing the WordPress server software and the initial setup process.

 
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 110

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

WordPress Tutorial 2: Terminology

An important part of learning any new piece of software is understanding the terminology it uses. Thankfully WordPress uses fairly simple names for everything that make it easy to start using the software.

Question has a verified solution.

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

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
This article discusses how to create an extensible mechanism for linked drop downs.
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.

635 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