Page 1 of 1

Sorting alphabetically an array.

Posted: Thu Jul 30, 2009 9:48 pm
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:

Re: Sorting alphabetically an array.

Posted: Thu Jul 30, 2009 9:57 pm
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");
}

Re: Sorting alphabetically an array.

Posted: Fri Jul 31, 2009 12:10 pm
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.