php - How do I sort a multi-dimensional array by value? -


I have an array as the following and I want to sort that array with the value of the key "attack" The first key of (15, 13, 18) is the ID of certain items from the database, so I do not want these keys to be changed when the array is sorted.

$ data = array ('15' => Array ('attack' = & gt; '45) Any help would be greatly appreciated.

This array is :

 '15', 'total' => 10 '),' 13 '= & gt; Array ('attack' => gtc: '25', 'rescue' => '15', 'total' => 10 '),' 18 '= & gt; Array ('attack' =>> '35', 'defense' => 15 ',' total '=> 10'));  

Use:

This function is an array , Such as using the array index user-defined comparison function, they maintain their connections with array elements.

This is used primarily when sorting the associative arrays is important when the actual element is important. Example:

  function cmp ($ a, $ b) {if ($ a ['attack'] == $ b ['attack' ]) {Return 0; } Return ($ one ['Attack'] & lt; $ b ['Attack'])? -1 1; } Usertet ($ data, 'CMP');  

If the values ​​are always string, then you can also use the cmp () function:

  function cmp ( $ A, $ B) {Return SRCMP ($ one ['Attack'], $ B ['Attack']); To sort in descending order, you only have to change the return values:  
  

Update:

Code> Return ($ ['Attack'] & lt; $ b ['Attack'])? 1 1; // ^ ---- ^

or to take the offer of Salal:

  $ b ['attack'] - $ a [' Invasion '];  

Comments