Jump to content

Php Sort Associative Array By Array Key


piznac

Recommended Posts

I have several arrays similar to this one:

[2] => Array
(
[0] => Array
(
[player] => piznac
[playerId] => 1
[positionRow] => 0
)


[1] => Array
(
[player] =>
[playerId] =>
[positionRow] =>
)


[2] => Array
(
[player] => Player 3
[playerId] => 3
[positionRow] => 1
)


[3] => Array
(
[player] =>
[playerId] =>
[positionRow] =>
)


)

 

How would I re-sort this array by the 'positionRow' key with still keeping the empty arrays. Something like this:

 

[2] => Array
(
[0] => Array
(
[player] => piznac
[playerId] => 1
[positionRow] => 0
)


[1] => Array
(
[player] => Player 3
[playerId] => 3
[positionRow] => 1
)


[2] => Array
(
[player] =>
[playerId] =>
[positionRow] =>
)


[3] => Array
(
[player] =>
[playerId] =>
[positionRow] =>
)


)

Link to comment
https://forums.phpfreaks.com/topic/269980-php-sort-associative-array-by-array-key/
Share on other sites

You can do this in php using one of two different methods -

 

1) Extract the positionrow values and use array_multisort. See Example #3 at the following link -array_multisort

 

2) You can write a call-back function that compares the values and use usort

 

or since this is probably data from a database query, why not just sort the data in the query?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.