0

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.

4

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but how can I see the ordered array, I am trying to print this but just get 1
You have to print the array, it is passed via reference: print_r($unOrderedArray);. The function only returns whether succeded or not.
Thanks I did var_dump($unOrderedArray['fields']); and it worked.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.