I'm using PHP. I have an array which has 1-256 items. Here is an example:
$arr[] = "(1.) Ben";
$arr[] = "Albert";
$arr[] = "Bill";
$arr[] = "(2.) Paul";
$arr[] = "(5.) Martin";
$arr[] = "(12.) Mike";
$arr[] = "(20.) John";
Question 1:
I would like to order the items alphabetically by names. So, the result should be this:
Albert
(1.) Ben
Bill
(20.) John
(5.) Martin
(12.) Mike
(2.) Paul
Question 2:
I also would like to order the items by 1) numbers and 2) names like this way:
(1.) Ben
(2.) Paul
(5.) Martin
(12.) Mike
(20.) John
Albert
Bill
How could I do the job with PHP?
It's sorting for Question 1
:
<?php
$arr[] = "(1.) Ben";
$arr[] = "Albert";
$arr[] = "Bill";
$arr[] = "(2.) Paul";
$arr[] = "(5.) Martin";
$arr[] = "(12.) Mike";
$arr[] = "(20.) John";
usort($arr, function($a, $b){
$a = explode(' ', $a, 2);
$a = (count($a) > 1) ? $a[1] : $a[0];
$b = explode(' ', $b, 2);
$b = (count($b) > 1) ? $b[1] : $b[0];
return strcmp($a, $b);
});
print_r($arr); // // Print array sorted for 'Question 1'
@EDIT And sorting for Question 2
:
$arr[] = "(1.) Ben";
$arr[] = "Albert";
$arr[] = "Bill";
$arr[] = "(2.) Paul";
$arr[] = "(5.) Martin";
$arr[] = "(12.) Mike";
$arr[] = "(20.) John";
usort($arr, function($a, $b){
$a = explode(' ', $a, 2);
$b = explode(' ', $b, 2);
if(count($a) > 1 && count($b) > 1)
{
$a = str_replace(['(', ')', '.'], '', $a[0]);
$b = str_replace(['(', ')', '.'], '', $b[0]);
return $a > $b;
}
else
{
return strcmp($a[0], $b[0]);
}
});
print_r($arr); // Print array sorted for 'Question 2'
php got sort functions: asort() for sorting by value and ksort() for sorting by key.
asort($arr); // now sorted by value.
ksort($arr); // now sorted by key.
As you are using index array so u can sort alphabetically by asort() function but for the another questions u have to make a function ie. The order in which u want to sort and then apply uasort() function. Link is php.net/manual/en/functions.uasort.php check the above link u might get clear