Home > Software design >  PHP: I need to sort an array by specific key
PHP: I need to sort an array by specific key

Time:01-22

I have an array like this:

$events = [[
  'col1' => $eventType,
  'col2' => $eventTime,
  'col3' => $eventLocation,
]];
Array (
  [0] => Array (
    [col1] => play
    [col2] => 39
    [col3] => home
  )
  [1] => Array (
    [col1] => card
    [col2] => 16
    [col3] => home
  )
  [2] => Array (
    [col1] => play
    [col2] => 67
    [col3] => home
  )
)

How could I sort these by the second column ($eventTime)? The correct order would be [1], [0], [2].

I've tried various sorting options but I'm unsure how to specify col2 as the key to sort by.

CodePudding user response:

You need to try the array_multisort() function. And maybe your question will be solved.

$col2 = array_column($events, 'col2');
array_multisort($col2, SORT_ASC, $events);

And your array will look like this

Array
(
    [0] => Array
        (
            [col1] => card
            [col2] => 16
            [col3] => home
        )

    [1] => Array
        (
            [col1] => play
            [col2] => 39
            [col3] => home
        )

    [2] => Array
        (
            [col1] => playsad
            [col2] => 40
            [col3] => home
        )

)

CodePudding user response:

You can use the usort() function to sort your array

$array=[...];
usort($array, function ($val1, $val2) {
    return $val2['col2'] < $val1['col2'];
});
var_dump($array);

CodePudding user response:

You can use array_multisort() :

$order_arr = array_column($events, 'col2');
array_multisort($order_arr, SORT_ASC, SORT_NUMERIC /* or other */, $events);

but it doesn't preserve keys: var_export($events):

array (
  0 => 
  array (
    'col1' => 'card',
    'col2' => 16,
    'col3' => 'home',
  ),
  1 => 
  array (
    'col1' => 'play',
    'col2' => 39,
    'col3' => 'home',
  ),
  2 => 
  array (
    'col1' => 'play',
    'col2' => 67,
    'col3' => 'home',
  ),
)

To preserve keys, see f.e. user's maSort() function: var_export(maSort($events, 'col2', 1));:

array (
  1 => 
  array (
    'col1' => 'card',
    'col2' => 16,
    'col3' => 'home',
  ),
  0 => 
  array (
    'col1' => 'play',
    'col2' => 39,
    'col3' => 'home',
  ),
  2 => 
  array (
    'col1' => 'play',
    'col2' => 67,
    'col3' => 'home',
  ),
)
  • Related