$users = array(
array(
'ID' => 1,
'name' => 'Lenivene Bezerra'
),
array(
'ID' => 2,
'name' => 'Michael S. Carnahan'
),
array(
'ID' => 3,
'name' => 'Billy T. Nealon'
)
);
echo "<pre>";
var_dump( $users );
echo "</pre>";
array_sort_by_column( $users, 'name', SORT_DESC );
echo "<pre>";
var_dump( $users );
echo "</pre>";
Created
September 16, 2019 14:00
-
-
Save lenivene/d7966cca253d0766ee5a70606b72c0b3 to your computer and use it in GitHub Desktop.
Array sort by column
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Array sort by column | |
* | |
* @author Lenivene | |
* @param array List | |
* @param string|array Columns name or single column | |
* @param int Order BY ASC|DESC. | |
* I recommend you use constant, Ex: SORT_ASC = 4 ( int ) | SORT_DESC = 3 ( int ) | |
*/ | |
function array_sort_by_column( &$array, $columns, $dir = SORT_ASC ){ | |
$sort_col = array(); | |
foreach( $array as $key => $row ){ | |
if( is_array( $columns ) ){ | |
foreach( $columns as $col ){ | |
$sort_col[ $key ] = ( is_object( $row ) ) ? $row->$col : $row[ $col ]; | |
} | |
} | |
else{ | |
$col = $columns; | |
$sort_col[ $key ] = ( is_object( $row ) ) ? $row->$col : $row[ $col ]; | |
} | |
} | |
array_multisort( $sort_col, $dir, $array ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment