如何通过PHP中内部数组的一个字段对多维数组进行排序?

Cam*_*oft 22 php arrays sorting multidimensional-array

假设我有一个模拟数据库表的数组.每个数组元素代表一行,每行内是另一个包含字段名称和值的数组.

Array
(
    [0] => Array
        (
            [name] => 'Sony TV'
            [price] => 600.00
        )

    [1] => Array
        (
            [name] => 'LG TV'
            [price] => 350.00
        )

    [2] => Array
        (
            [name] => 'Samsung TV'
            [price] => 425.00
        )  
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是按价格对行(外部数组元素)进行排序.下面是我想要实现的一个例子:

Array
(
    [0] => Array
        (
            [name] => 'LG TV'
            [price] => 350.00
        )

    [1] => Array
        (
            [name] => 'Samsung TV'
            [price] => 425.00
        )

    [2] => Array
        (
            [name] => 'Sony TV'
            [price] => 600.00
        )        
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我不需要保留外部数组的键.

Dan*_*umb 38

您需要使用usort,这是一个通过用户定义的函数对数组进行排序的函数.就像是:

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

usort($yourArray,"cmp")
Run Code Online (Sandbox Code Playgroud)


rf1*_*234 20

它只是一个班轮

array_multisort( array_column($yourArray, "price"), SORT_ASC, $yourArray );
Run Code Online (Sandbox Code Playgroud)

你也可以在这里找到它:http://php.net/manual/en/function.array-multisort.php

在该手册页上搜索"array_column".

  • 没错,Ifedi。人们不应该使用旧的PHP版本。甚至现在不赞成使用PHP 7.0。最好使用PHP 7.2或7.3 (2认同)

Fel*_*ing 14

你可以使用usort():

function sort($a, $b) {
    if ($a['price'] == $b['price']) return 0;
    return ($a['price'] > $b['price']) ? 1 : -1;
}

usort($array, 'sort');
Run Code Online (Sandbox Code Playgroud)

如果你创建一个这样的类来重用代码,那就更好了:

class FieldSorter {
    public $field;

    function __construct($field) {
        $this->field = $field;
    }

    function cmp($a, $b) {
        if ($a[$this->field] == $b[$this->field]) return 0;
        return ($a[$this->field] > $b[$this->field]) ? 1 : -1;
    }
}

$sorter = new FieldSorter('price');    
usort($array, array($sorter, "cmp"));
Run Code Online (Sandbox Code Playgroud)

这样,您可以轻松地按其他字段排序.

虽然您说不必保留外部数组的键,但您可以通过使用uasort()而不是使用来轻松实现usort.


Don*_*nic 9

这与接受的答案基本相同,但多年来 PHP 中添加了一些新功能,以使其更方便地使用usort

$column = 'price';
usort($table, function($a, $b) use ($column) {
    return $a[$column] <=> $b[$column];
});
Run Code Online (Sandbox Code Playgroud)

您现在可以为比较回调使用匿名函数(从 PHP 5.3 开始),并且 PHP 7 引入了组合比较运算符( <=>),它允许您减少比较逻辑

if ($a['price'] == $b['price']) return 0;
return ($a['price'] > $b['price']) ? 1 : -1;
Run Code Online (Sandbox Code Playgroud)

到单个表达式

return $a[$column] <=> $b[$column];
Run Code Online (Sandbox Code Playgroud)