0

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

<?php 

  $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.

Is this posibble?

Álvaro
  • 2,255
  • 1
  • 22
  • 48
  • Does this answer your question? [How to sort an array of associative arrays by value of a given key in PHP?](https://stackoverflow.com/questions/1597736/how-to-sort-an-array-of-associative-arrays-by-value-of-a-given-key-in-php) – ADyson Jul 30 '21 at 10:25
  • Does this answer your question? [How to Sort a Multi-dimensional Array by Value](https://stackoverflow.com/questions/2699086/how-to-sort-a-multi-dimensional-array-by-value) – aaandri98 Jul 30 '21 at 10:25
  • It does not print the results I am trying to do `var_dump(usort($unOrderedArray, 'sortByOrder'));` but I just get `bool(true)` – Álvaro Jul 30 '21 at 10:33
  • The link I provided shows a different solution. Please take a look. – ADyson Jul 30 '21 at 10:35

1 Answers1

1

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);
diegopso
  • 457
  • 3
  • 11
  • Thanks, but how can I see the ordered array, I am trying to print this but just get `1` – Álvaro Jul 30 '21 at 10:34
  • You have to print the array, it is passed via reference: `print_r($unOrderedArray);`. The function only returns whether succeded or not. – diegopso Jul 30 '21 at 10:35
  • 1
    Thanks I did `var_dump($unOrderedArray['fields']);` and it worked. – Álvaro Jul 30 '21 at 10:36