PHP Snippets
array_natcase
Information
(PHP Version >= 3)Functions used in this snippet: natcasesort, array_reverse.
Description
array array_natcase( str key, array array[, str ascdesc] )
Sorts the associative array array by the associative array key key with natcasesort. It maintains all keys and can be sorted ascending or descending by setting ascdesc to either asc, or desc. The function returns the newly array sorted array.
Snippet
<?php
function array_natcase($key, $array, $ascdesc='asc')
{
$temp = array();
$final = array();
foreach($array as $id=>$value)
{
$temp[$id] = $value[$key];
}
natcasesort($temp);
foreach($temp as $id=>$value)
{
$final[$id] = $array[$id];
}
if($ascdesc{0} === 'd')
{
$final = array_reverse($final, true);
}
return $final;
}
?>
Example
array_natcase Can be used in the following way:
<?php
$array = array(
'a'=>array('x'=>10, 'other'=>'egh'),
'q'=>array('x'=>9, 'other'=>'blah'),
'7'=>array('x'=>1, 'other'=>'rawr'),
'6'=>array('x'=>22, 'other'=>'abcd'));
$array = array_natcase('x', $array);
//outputs the array in the following order
// 7, q, a, 6
?>
0 Responses to array_natcase