NYCPHP Meetup

NYPHP.org

[nycphp-talk] How to sort a multi-dimensional array by a given key?

Timothy Boyden tboyden at supercoups.com
Mon May 7 11:57:36 EDT 2007


Scott,

That worked great!

Thanks,

Tim 

-----Original Message-----
From: talk-bounces at lists.nyphp.org [mailto:talk-bounces at lists.nyphp.org]
On Behalf Of Scott Trudeau
Sent: Monday, May 07, 2007 11:49 AM
To: NYPHP Talk
Subject: Re: [nycphp-talk] How to sort a multi-dimensional array by a
given key?

I'm sure there's probably a better way to do this, but uasort() sorts an
array using a callback provided callback function for item comparisons
-- which you can use to compare the specific key you want to sort by.
It seems like there should be a more generic way to do this by providing
the name of the key on which you want to sort.


$franchises['SCID1'] = SCNYC
$franchises['SCID1']['BusinessName'] = SuperCoups of NY City
$franchises['SCID1']['DistanceFromCustomer'] = 20 $franchises['SCID2'] =
SCBUFF $franchises['SCID2']['BusinessName'] = SuperCoups of Buffalo
$franchises['SCID2']['DistanceFromCustomer'] = 10

uasort($franchises, "cmp_distance");

function cmp_distance($a, $b) {
	if($a['DistanceFromCustomer'] == $b['DistanceFromCustomer'])
return 0;	
	return ($a['DistanceFromCustomer'] < $b['DistanceFromCustomer'])
? -1 : 1; }



On 5/7/07, Timothy Boyden <tboyden at supercoups.com> wrote:
>
>
> Hi All,
>
> I have a multi-dimensional array such as:
>
> $franchises['SCID1'] = SCNYC
> $franchises['SCID1']['BusinessName'] = SuperCoups of NY City 
> $franchises['SCID1']['DistanceFromCustomer'] = 20
>
> $franchises['SCID2'] = SCBUFF
> $franchises['SCID2']['BusinessName'] = SuperCoups of Buffalo 
> $franchises['SCID2']['DistanceFromCustomer'] = 10
>
> How can I sort this array so the businesses are sorted by the 
> DistanceFromCustomer key?
>
> Thanks for the help in advance,
>
> Tim
>
>
> ---------------------------
> Timothy Boyden
>
> Network Administrator
>
> tboyden at supercoups.com
>
>
>
> SuperCoups(r)
>
>
>
> 350 Revolutionary Drive | E. Taunton, MA 02718
>
> 508-977-2034  | www.supercoups.com
>
>
>
> We Support Alex's Lemonade Stand Foundation,
>
> "Fighting Childhood Cancer One Cup At A Time"
>
> Donations Accepted at: www.firstgiving.com/SuperCoups
>
> ---------------------------
>
> Local Coupons. Super Savings.(r)
>
> _______________________________________________
> New York PHP Community Talk Mailing List 
> http://lists.nyphp.org/mailman/listinfo/talk
>
> NYPHPCon 2006 Presentations Online
> http://www.nyphpcon.com
>
> Show Your Participation in New York PHP 
> http://www.nyphp.org/show_participation.php
>
_______________________________________________
New York PHP Community Talk Mailing List
http://lists.nyphp.org/mailman/listinfo/talk

NYPHPCon 2006 Presentations Online
http://www.nyphpcon.com

Show Your Participation in New York PHP
http://www.nyphp.org/show_participation.php



More information about the talk mailing list