Skip to content

Instantly share code, notes, and snippets.

@lenivene
Created September 16, 2019 14:00
Show Gist options
  • Save lenivene/d7966cca253d0766ee5a70606b72c0b3 to your computer and use it in GitHub Desktop.
Save lenivene/d7966cca253d0766ee5a70606b72c0b3 to your computer and use it in GitHub Desktop.
Array sort by column

Example

$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>";
<?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