phparrayssortingmultidimensional-array

Sort a multi-dimensional array by a column


I am trying to order arrays inside a quite nested array according to a property inside the arrays that need sorting.

$unOrderedArray = array(
    'fields' => array(
      array(
        'key' => 'field_60f6e595c18cc',
         'name' => 'Should be last',
      ),
      array(
        'key' => 'field_60f6bcf3e0b87',
        'name' => 'Should be second',
      ),
      array(
        'key' => 'field_60f6adb77c6f3',
        'name' => 'Should be first',
      )
    )
  );    

So the key property has a value that could be ordered alphabetically.


Solution

  • I believe you need to use usort, where you can specify a custom sorting function. The solution would be:

      usort($unOrderedArray['fields'], function($a, $b) {
         return  $a['key'] > $b['key'] ? 1 : -1;
      });
    

    Obs.: I return integers in the function to avoid warnings.

    The usort function only returns a bool informing whether succeded or not. The array is passed via reference and its value is changed while sorting. Thus, to observe the results one has to print the original array.

      print_r($unOrderedArray);