Solved

Sort Associative PHP Array on value but maintain key order

Posted on 2008-10-28
6
456 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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
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 108

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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
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…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

706 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now