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
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?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.