我如何排序值多维数组? [英] How do I sort a multi-dimensional array by value?

查看:126
本文介绍了我如何排序值多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组如下,我想订购了关键的攻击的值数组。数组的第一个键(15,13,18)从数据库中的一些特定条目的ID,所以我不想当数组排序要改变这些键。任何帮助将大大AP preciated。

这是该数组:

  $数据=阵列(
    '15'=>阵列(
        攻击=> '45','国防'=> '15','总'=> '10'
    )
    '13'=>阵列(
        攻击=> '25','国防'=> '15','总'=> '10'
    )
    '18'=>阵列(
        攻击=> '35','国防'=> '15','总'=> '10'
    )
);


解决方案

使用 uasort()


  

这个函数对一个数组,使得数组的索引保持其相关性与它们所关联数组元素,使用用户定义的比较函数。


  
  

这是排序关联数组时,在实际元素的顺序是显著主要用。


例如:

 函数CMP($ A,$ B){
    如果($ A ['攻击'] == $ B ['攻击']){
        返回0;
    }
    返回($ A ['攻击'< $ B ['攻击'])? -1:1;
}uasort($数据,CMP);

如果该值始终为字符串,还可以使用 STRCMP () CMP()功能:

 函数CMP($ A,$ B){
    返回STRCMP($ A ['攻击'],$ B ['攻击']);
}

更新:

要以降序排列,你只需要改变返回值:

 收益率($ A ['攻击'< $ B ['攻击'])? 1:-1;
// ^ ^ ----

或拿起@ salathe的建议:

 返回$ B ['攻击']  -  $ A ['攻击'];

I have an array as following and I want to order that array by the value of the key "attack". First keys of the arrays (15, 13, 18) are ID of some certain item from database, so I don't want these keys to be changed when the array is sorted. Any help would be greatly appreciated.

This is the array:

$data = array(
    '15' => array(
        'attack' => '45', 'defence' => '15', 'total' => '10'
    ),
    '13' => array(
        'attack' => '25', 'defence' => '15', 'total' => '10'
    ),
    '18' => array(
        'attack' => '35', 'defence' => '15', 'total' => '10'
    )
);

解决方案

Use uasort():

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with, using a user-defined comparison function.

This is used mainly when sorting associative arrays where the actual element order is significant.

Example:

function cmp($a, $b) {
    if ($a['attack'] == $b['attack']) {
        return 0;
    }
    return ($a['attack'] < $b['attack']) ? -1 : 1;
} 

uasort($data, 'cmp');

If the values are always strings, you can also use strcmp() in the cmp() function:

function cmp($a, $b) {
    return strcmp($a['attack'], $b['attack']);
} 

Update:

To sort in descending order you just have to change the return values:

return ($a['attack'] < $b['attack']) ? 1 : -1;
//                                     ^----^

or to pick up @salathe's proposal:

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

这篇关于我如何排序值多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆