Sort array of arrays based on value inside the inner array

I have an array of arrays like the first array.
I would like to sort it in the order based on key3 in the second inner array
note I need to keep the keys from both arrays
How can I do this?

[1] => Array
(
[key1] => 123
[key2] => ‘apple’
[key3] => 10
[key4] => ‘comment1’
)

[2] => Array
(
[key1] => 234
[key2] => ‘PEAR’
[key3] => 4
[key4] => ‘comment2’
)

[3] => Array
(
[key1] => 456
[key2] => ‘ORANGE’
[key3] => 5
[key4] => ‘comment3’
)

[4] => Array
(
[key1] => 679
[key2] => ‘grape’
[key3] => 1
[key4] => ‘comment4’
)

The result would look like this:
[4] => Array
(
[key1] => 679
[key2] => ‘grape’
[key3] => 1
[key4] => ‘comment4’
)
[2] => Array
(
[key1] => 234
[key2] => ‘PEAR’
[key3] => 4
[key4] => ‘comment2’
)
[3] => Array
(
[key1] => 456
[key2] => ‘ORANGE’
[key3] => 5
[key4] => ‘comment3’
)
[1] => Array
(
[key1] => 123
[key2] => ‘apple’
[key3] => 10
[key4] => ‘comment1’
)

See - PHP: uasort - Manual

Call-back function to sort using the key3 entries -

function sorter(array $a, array $b) {
    return $a['key3'] <=> $b['key3'];
}

Assuming your data is in $data -

uasort($data, 'sorter');

Thank you. Worked a treat :slight_smile:

Sponsor our Newsletter | Privacy Policy | Terms of Service