Trabla: php: sort assoc array by key ascending or descending
Solving:
Use ksort to sort ascending ( from low to high ) by key
Use krsort to sort descending ( from high to low ) by key
Examples:
<?php
$arr = array(
'2015-01-10' => array( "name"=>"Test2", "status"=>"failed" ),
'2013-01-10' => array( "name"=>"Test1", "status"=>"passed" ),
'2016-01-10' => array( "name"=>"Test3", "status"=>"passed" ),
);
ksort( $arr );
print_r($arr);
/*
Result - ascending from low to high:
Array (
[2013-01-10] => Array ( [name] => Test1 [status] => passed )
[2015-01-10] => Array ( [name] => Test2 [status] => failed )
[2016-01-10] => Array ( [name] => Test3 [status] => passed )
)
*/
krsort( $arr );
print_r( $arr);
/*
Result - descending from high to low:
Array
(
[2016-01-10] => Array ( [name] => Test3 [status] => passed )
[2015-01-10] => Array ( [name] => Test2 [status] => failed )
[2013-01-10] => Array ( [name] => Test1 [status] => passed )
)
*/
Official Docs:
http://php.net/manual/en/array.sorting.php
No comments:
Post a Comment