PHP has very handy functions to sort arrays e.g. sort. A simple use of this can be as follows:
$arr = array(5,4,1,2);Now what if we have to sort array on keys? We can use ksort function. For example, consider following code:
sort($arr)
print_r($arr);
$arr = array("y" => "second", "x" => "first", "z" => "third");Now we made example a bit complicate. Consider we have following array:
ksort($arr);
print_r($arr);
$arr = array( 0 => array("name" => "w3", "city" => "city3"),Now we want to sort this array on the basis of name. To achieve this one may use the loops. But I found very simple solution of this one. Use usort. Take a look at following code. It will sort array on the basis of name:
1=> array("name" => "w1", "city" => "city1") ,
2 => array("name" => "w2", "city" => "city2") ,
);
Now what if we want to sort array first on name and then on city. It is same as we use ORDER BY clause in SQL. We can easily achieve this by following code:
function mySort($a, $b)
{
return strcasecmp($a['name'], $b['name']);
}
usort($arr, "mySort");
echo "<pre>";
print_r($arr);
Now by using above technique we can sort on nth level.
function mySort($a, $b)
{
if(strcasecmp($a['name'], $b['name']) == 0)
{
return strcasecmp($a['city'], $b['city']);
}
return strcasecmp($a['name'], $b['name']);
}
No comments:
Post a Comment