I have some languages stored in my database as follows:
id | code | name
--------------------------------------
1 | en_GB | English, United Kingdom
2 | pt_BR | Portugese, Brazil
3 | it_IT | Italian, Italy
4 | hi_IN | Hindi, India
5 | es_BR | Spanish, Brazil
6 | ur_IN | Urdu, India
I want to get these results and sort (or sort after I get all results), so I get the results first by ordered Country Code (second part of code) and then by Locale Code (first part of code) so:
$languages = [
0 => [
'code' => 'es_BR'
],
1 => [
'code' => 'pt_BR'
],
2 => [
'code' => 'en_GB'
],
3 => [
'code' => 'hi_IN'
],
4 => [
'code' => 'ur_IN'
],
5 => [
'code' => 'it_IT'
]
];
I've tried looping through each language and taking out the second part and storing an array of the Country Codes and then sorting them using asort($countryCodes);
, which did sort by Country Code (GB), but I'm stuck sorting that list out by Locale Code (en).
Any help will be appreciated, thanks!
I have come up with the following and it has given me what I needed:
$languages = $this->getOrderedLanguages();
protected function getOrderedLanguages()
{
$languages = Language::orderBy('code')->get();
// Sort out the other languages by country code (e.g. sort by GB in code en_GB)
// Create array for each country code and store array key from original list
$countryCodes = [];
foreach($languages as $key => $language) {
$countryCodes[$language->locale_code][] = [
'id' => $key,
'language' => $language->language_code
];
}
ksort($countryCodes);
$orderedLanguages = [];
// Go through each country code and sort the languages in there by locale code (e.g. sort by en in code en_GB)
foreach($countryCodes as &$countryCode) {
asort($countryCode);
foreach($countryCode as $language) {
$orderedLanguages[] = $allLanguages[$language['id']];
}
}
// Return ordered array
return $orderedLanguages;
}
This has given me the following result:
$languages = [
0 => [
'code' => 'es_BR'
],
1 => [
'code' => 'pt_BR'
],
2 => [
'code' => 'en_GB'
],
3 => [
'code' => 'hi_IN'
],
4 => [
'code' => 'ur_IN'
],
5 => [
'code' => 'it_IT'
]
];
I guess array_multisort is what you are looking for.
You would use usort() - http://php.net/usort
My suggestion would be:
function cmp($a, $b){
return strcmp($a["code"], $b["code"]);
}
usort($languages, "cmp");
print_r($languages);
Hope this will help you
Please try with other version of code :
$fArray=array();
foreach($languages as $languages){
array_push($fArray,$languages);
}
sort($fArray);
print_r($fArray);
`OR`
array_multisort($languages);
print_r($languages);
Following are the generated array for both function :
Array
(
[0] => Array
(
[code] => en_GB
)
[1] => Array
(
[code] => es_BR
)
[2] => Array
(
[code] => hi_IN
)
[3] => Array
(
[code] => it_IT
)
[4] => Array
(
[code] => pt_BR
)
[5] => Array
(
[code] => ur_IN
)
)