简体   繁体   English

如何按值对多维数组进行排序?

[英]How do I sort a multi-dimensional array by value?

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. 数组的第一个键(15, 13, 18)是来自数据库的某个特定项的ID,因此我不希望在对数组进行排序时更改这些键。 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() : 使用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: 如果值总是字符串,您还可以在cmp()函数中使用strcmp()

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: 或者接受@ salathe的提议:

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

Simply use array_multisort 只需使用array_multisort

foreach ($data as $key => $row) {
    $attack[$key]  = $row['attack'];
}

// Sort the data with attack descending
array_multisort($attack, SORT_DESC, $data);

Hope this helps. 希望这可以帮助。

$result = [];
foreach ($data as $key => $value) {
    $result[$key] = $value;
    asort($result[$key]);
}
print_r($result);

Hope this helps !!! 希望这可以帮助 !!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM