如何按嵌套在其中的元素对 PHP 数组进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3701855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:46:17  来源:igfitidea点击:

How do I sort a PHP array by an element nested inside?

phparrayssortingmultidimensional-arrayusort

提问by geerlingguy

I have an array like the following:

我有一个如下所示的数组:

Array
(
    [0] => Array
        (
            'name' => "Friday"
            'weight' => 6
        )
    [1] => Array
        (
            'name' => "Monday"
            'weight' => 2
        )
)

I would like to grab the last values in that array (the 'weight'), and use that to sort the main array elements. So, in this array, I'd want to sort it so the 'Monday' element appears before the 'Friday' element.

我想获取该数组中的最后一个值(“权重”),并使用它对主要数组元素进行排序。所以,在这个数组中,我想对它进行排序,以便 'Monday' 元素出现在 'Friday' 元素之前。

回答by codaddict

You can use usortas:

您可以usort用作:

function cmp($a, $b) {
   return $a['weight'] - $b['weight'];
}

usort($arr,"cmp");

回答by Geo

Can be done using an anonymous function.

可以使用匿名函数来完成。

Also if your 'weight' is a stringuse one of the other returns (see the commented out lines):

此外,如果您的“重量”是字符串,请使用其他返回之一(请参阅注释掉的行):

<?php

$arr = array(
    0 => array (
        'name'   => 'Friday',
        'weight' => 6,
    ),
    1 => array (
        'name'   => 'Monday',
        'weight' => 2,
    ),
);

// sort by 'weight'
usort($arr, function($a, $b) { // anonymous function
    // compare numbers only
    return $a['weight'] - $b['weight'];

    // compare numbers or strings
    //return strcmp($a['weight'], $b['weight']);

    // compare numbers or strings non-case-sensitive
    //return strcmp(strtoupper($a['weight']), strtoupper($b['weight']));
});

var_export($arr);

/*
array (
    0 => array (
        'name'   => 'Monday',
        'weight' => 2,
    ),
    1 => array (
        'name'   => 'Friday',
        'weight' => 6,
    ),
)
*/

回答by Richard Ayotte

You can also use an anonymous function.

您还可以使用匿名函数。

usort($items, function($a, $b) {
    return $a['name'] > $b['name'];
});

回答by Konel Sum

Agree with usort, I also sometimes use array_multisort (http://ca2.php.net/manual/en/function.usort.php) example 3, sorting database results. You could do something like:

同意usort,我有时也用array_multisort(http://ca2.php.net/manual/en/function.usort.php)例子3,对数据库结果进行排序。你可以这样做:

<?php
$days = array(
  array('name' => 'Friday', 'weight' => 6),
  array('name' => 'Monday', 'weight' => 2),
);

$weight = array();
foreach($days as $k => $d) {
  $weight[$k] = $d['weight'];
}

print_r($days);

array_multisort($weight, SORT_ASC, $days);

print_r($days);
?>

Output:

输出:

Array
(
    [0] => Array
        (
            [name] => Friday
            [weight] => 6
        )

    [1] => Array
        (
            [name] => Monday
            [weight] => 2
        )

)
Array
(
    [0] => Array
        (
            [name] => Monday
            [weight] => 2
        )

    [1] => Array
        (
            [name] => Friday
            [weight] => 6
        )

)

回答by d.raev

If the filed you sort by is string like titlename,
array_multisort+ Flags for Natural Sortingand CaseInSensitivityare the way to go:

如果您排序的文件是类似字符串titlename,则
array_multisort+ Flags for Natural SortingCaseInSensitivity可行的方法:

$sort_by_title = array();
foreach($items as $item) {
  $sort_by_title [] = $item['title'];
}
array_multisort($sort_by_title , SORT_ASC, SORT_NATURAL | SORT_FLAG_CASE, $items );

回答by Barry

NOTE, if the element you are sorting on is a float like .0534 and .0353 (like for a percentage), then you have to multiply both by 1000. not sure why frankly... it appears that usort seems to compare the integer values.

注意,如果您要排序的元素是像 .0534 和 .0353 之类的浮点数(例如百分比),那么您必须将两者都乘以 1000。坦率地说,不知道为什么......似乎 usort 似乎比较了整数值。

took me awhile to figure that one out...

我花了一段时间才弄明白...

and 2 tips that may not be immediately obvious:

和 2 个可能不是很明显的提示:

  1. if your arrays are objects, you can use return $a->weight - $b->weight of course
  2. if you return $b->weight - $a->weight, it will sort desending.
  1. 如果你的数组是对象,你当然可以使用 return $a->weight - $b->weight
  2. 如果您返回 $b->weight - $a->weight,它将排序降序。

回答by d2burke

Here's a cool function that might help:

这是一个很酷的功能,可能会有所帮助:

function subval_sort($a,$subkey,$sort) {
    foreach($a as $k=>$v) {
        $b[$k] = strtolower($v[$subkey]);
    }
    if($b)
    {
        $sort($b);
        foreach($b as $key=>$val) {
            $c[] = $a[$key];
        }
        return $c;
    }
}

Send in the array as $athe key as $subkeyand 'asort' or 'sort' for the $sortvariable

将数组作为$a键发送,$subkey并为$sort变量发送“asort”或“sort”