RSS

Tag Archives: Sort array on multiple columns

Sort array on multiple columns

<?php

$sorted = array_orderby($data, ‘col1’, SORT_ASC, ‘col2’, SORT_ASC);

function array_orderby() {
$args = func_get_args();
$data = array_shift( $args );

if ( ! is_array( $data ) ) {
return array();
}

$multisort_params = array();
foreach ( $args as $n => $field ) {
if ( is_string( $field ) ) {
$tmp = array();
foreach ( $data as $row ) {
$tmp[] = $row[ $field ];
}
$args[ $n ] = $tmp;
}
$multisort_params[] = &$args[ $n ];
}

$multisort_params[] = &$data;

call_user_func_array( ‘array_multisort’, $multisort_params );
return end( $multisort_params );
}

?>

Advertisements
 
Leave a comment

Posted by on October 11, 2014 in Core PHP

 

Tags: ,