Sorting alphabetically an array.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lovelf
Forum Contributor
Posts: 153
Joined: Wed Nov 05, 2008 12:06 am

Sorting alphabetically an array.

Post by lovelf »

Code: Select all

$countries= array(
 
'Zambia' => array (
'CIP' => 'Chipata, Zambia (CIP)',
'KAA' => 'Kasama, Zambia (KAA)',
'ZKB' => 'Kasaba Bay, Zambia (ZKB)',
'LVI' => 'Livingstone, Zambia - Livingstone (LVI)',
'LUN' => 'Lusaka, Zambia - Lusaka International (LUN)',
'MFU' => 'Mfuwe, Zambia - Mfuwe (MFU)',
'NLA' => 'Ndola, Zambia - Ndola (NLA)',
'KIW' => 'Southdowns, Zambia - Southdowns (KIW)',
),
 
'Zimbabwe' => array (
'BUQ' => 'Bulawayo, Zimbabwe - Joshua Mqabuko Nkomo (BUQ)',
'BFO' => 'Chiredzi, Zimbabwe - Chiredzi Buffalo Range (BFO)',
'VFA' => 'Victoria Falls, Zimbabwe - Victoria Falls International (VFA)',
'UTA' => 'Mutare, Zimbabwe - Mutare Grand Reef (UTA)',
'GWE' => 'Gweru, Zimbabwe (GWE)',
'HRE' => 'Harare, Zimbabwe - Harare International (HRE)',
'KAB' => 'Kariba, Zimbabwe - Kariba International (KAB)',
'MVZ' => 'Masvingo, Zimbabwe - Masvingo (MVZ)',
'VFA' => 'Victoria Falls, Zimbabwe (VFA)',
'GWE' => 'Gwert, Zimbabwe - Gweru Thornhill (GWE)',
'WKM' => 'Hwange National Park, Zimbabwe - Hwange National Park (WKM)',
),
 
);
I need somehow to get what's inside Zambia and Zimbabwe sorted alphabetically by the value after the key.

I put this code up as an example, I would like to know how to sort arrays alphabetically which are inside other arrays.

Thanks. :oops:
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Sorting alphabetically an array.

Post by requinix »

Write a function that takes two arguments (values from a $countries[...] subarray) and decides which one should come first.

Then use it with uasort, passing each array in $countries to it:

Code: Select all

foreach ($countries as $key => $value) {
    uasort($countries[$key], "function name");
}
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Sorting alphabetically an array.

Post by pickle »

It could be as simple as:

Code: Select all

sort($countries['Zambia']);
sort($countries['Zimbabwe']);
Though I haven't tested. You may need to copy $countries['Zambia'] etc into a new array, sort() that array, then put it back into $countries['Zambia'] etc.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply