NYCPHP Meetup

NYPHP.org

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

Dan Cech dcech at phpwerx.net
Mon May 7 11:51:24 EDT 2007


Timothy Boyden 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?

Firstly, your array above looks somewhat suspect, you might want to use
actual code for your example.

That said, try the following:

$franchises = array();
$franchises['SCID1'] = array();
$franchises['SCID1']['BusinessName'] = 'SuperCoups of NY City';
$franchises['SCID1']['DistanceFromCustomer'] = 20;
$franchises['SCID2'] = array();
$franchises['SCID2']['BusinessName'] = 'SuperCoups of Buffalo';
$franchises['SCID2']['DistanceFromCustomer'] = 10;

uasort($franchises,create_function('$a,$b','return
strnatcmp($a["DistanceFromCustomer"],$b["DistanceFromCustomer"]);'));

Dan



More information about the talk mailing list