按照内部数组键值排序数组

8

我有一个像下面提到的数组

Array
(
[6] => Array
    (
        [name] => Extras
        [total_products] => 0
        [total_sales] => 0
        [total_affiliation] => 0
    )

[5] => Array
    (
        [name] => Office Products
        [total_products] => 7
        [total_sales] => 17
        [total_affiliation] => 8
    )

[1] => Array
    (
        [name] => Hardware Parts
        [total_products] => 6
        [total_sales] => 0
        [total_affiliation] => 0
    )

)

目前,顺序为:Extras、Office Products、Hardware Parts

我希望按照内部数组的 total_sales 降序排列来对主数组进行排序

因此,顺序将为:Office Products、Extras、Hardware Parts

有什么帮助吗?


通常情况下,每当您需要以特殊方式对数组进行排序且常规排序函数无法胜任时,您应该查看u-sort函数族 - user456814
3个回答

17

PHP 5.3:

usort($array, function ($a, $b) { return $b['total_sales'] - $a['total_sales']; });

PHP 5.2及以前的版本:

usort($array, create_function('$a,$b', 'return $b["total_sales"] - $a["total_sales"];'));

2
+1,太快了,我正在写那个。 - Stuti
@deceze:如果我使用PHP 5.2版本和5.3或更高版本呢? - I-M-JM
@I-M 不太确定你的意思。如果你需要使其兼容所有PHP版本,请使用PHP 5.2-版本。这仍然适用于PHP 5.3+。只有PHP 5.3语法不支持5.2-。 - deceze
1
@sini 是的,同样的方法对于 uasort 也适用。 - deceze
1
@Kamlesh https://dev59.com/_WQm5IYBdhLWcg3wwxLF#17364128 - deceze
显示剩余2条评论

3

使用自定义函数和usort

<?php
function custom_sale_sort($a, $b)
{
    if ($a['total_sales'] < $b['total_sales'])
        return 1;
    elseif ($a['total_sales'] == $b['total_sales'])
        return 0;
    else
        return -1;
}

usort($array, 'custom_sale_sort');

如果您需要按照另一方向对数组进行排序,则在自定义函数中切换(1,-1)的值。


1
可以通过简单地返回 $a['total_sales'] 和 $b['total_sales'] 的差异来简化 if-else,因为 usort 检查的是负数和正数而不是大小来分配顺序。 - DhruvPathak

2

以下是可用于进行多维排序的类:

注意:您必须使用PHP5

class MultiDimensionSort
{
    const ASCENDING = 0,DESCENDING = 1;

    public  $sortColumn,$sortType;

    public function __construct($column = 'price', $type = self::ASCENDING)
    {
        $this->column = $column;
        $this->type = $type;
    }

    public function cmp($a, $b)
    {
        switch($this->type)
        {
            case self::ASCENDING:
                return ($a[$this->column] == $b[$this->column]) ? 0 : (($a[$this->column] < $b[$this->column]) ? -1 : 1);
            case self::DESCENDING:
                return ($a[$this->column] == $b[$this->column]) ? 0 :(($a[$this->column] < $b[$this->column]) ? 1 : -1);
            default:
                assert(0); // unkown type
        }
    }
}

如果您有一个名为summary的数组,其中包含上述数组,则可以按照以下语句进行排序。 // 假设您的数组变量是$summary

$s = new MultiDimensionSort('total_sales', MultiDimensionSort::DESCENDING); // sort by total_sales

usort($summary, array($s, 'cmp'));
print"<pre>";print_r($summary);

欢呼! 也许这会对你有所帮助。


2
这难道不是有点过度杀伤力了吗? :) - deceze
一个整个类的包装器,只需要一行代码就可以完成...?如果你正在使用面向对象编程,为什么不进一步抽象化,得到像 MultiDimensionSort::sort($array, 'total_sales', MultiDimensionSort::DESCENDING) 这样的东西呢? - deceze

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接