Sorting Arrays in PHP – How to Sort Multi-dimensional Array by Value

The simplest method is to use the default function in php: array_multisort and array_column.

Below you have a functional example of sorting,

<pre>
<?php 

$array = [
  [
  'key1' => 'abc',
  'key2' => 'test2',
  'key3' => -1,
  ],

  [
  'key1' => 'xyz',
  'key2' => 'test1',
  'key3' => 1,
  ],

  [
  'key1' => 'abcdefchijklmnop',
  'key2' => 'test3',
  'key3' => 120,
  ],
];

array_multisort( array_column($array, 'key1') , SORT_DESC, $array);

var_export($array);

?>
</pre>

below you have the results of sorting in descending order of a multi-key array variable:

array (
  0 => 
  array (
    'key1' => 'xyz',
    'key2' => 'test1',
    'key3' => 1,
  ),
  1 => 
  array (
    'key1' => 'abcdefchijklmnop',
    'key2' => 'test3',
    'key3' => 120,
  ),
  2 => 
  array (
    'key1' => 'abc',
    'key2' => 'test2',
    'key3' => -1,
  ),
)

Happy Codings 🙂

byrev Written by:

Be First to Comment

    Leave a Reply

    Your email address will not be published. Required fields are marked *