【问题标题】:sorting array based on inner-array key-value [duplicate]基于内部数组键值对数组进行排序
【发布时间】:2011-09-25 17:10:26
【问题描述】:

我有一个如下所述的数组

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
    )

)

现在,订单是:附加品、办公用品、硬件零件

我想对主数组进行排序,使其按内部数组的 total_sales 以 desc 顺序排序

因此订单将是:办公产品、附加产品、硬件零件

任何帮助家伙

【问题讨论】:

  • 一般来说,当您需要以特殊方式对数组进行排序而常规排序功能无法完成这项工作时,您应该查看u-sort family of functions

标签: php


【解决方案1】:

使用自定义函数和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) 值。

【讨论】:

  • 可以从 if-else 中简化,只需返回 $a['total_sales'] 和 $b['total_sales'] 的差异,因为 usort 检查 -ve,+ve 而不是分配顺序的大小。
【解决方案2】:

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"];'));

【讨论】:

  • +1,太快了,我正在写这个
  • @deceze: 如果我使用 5.3 或更高版本的 PHP 5.2 版本怎么办?
  • @I-M 不确定你在说什么。如果您需要使其与所有 PHP 版本兼容,请使用 PHP 5.2- 版本。这仍然适用于 PHP 5.3+。只有 PHP 5.3 语法在 5.2-中不支持。
  • @sini 是的,同样的事情也适用于uasort
【解决方案3】:

这是你可以用来进行多维排序的类

注意:你必须有 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);

干杯! 可能对你有帮助

【讨论】:

  • 这不是有点矫枉过正吗? :)
  • 一个完整的类包装器,单线可以做......?如果你要 OO,为什么不进一步抽象它以获得类似 MultiDimensionSort::sort($array, 'total_sales', MultiDimensionSort::DESCENDING) 的东西?
猜你喜欢
  • 2014-07-19
  • 1970-01-01
  • 1970-01-01
  • 2021-01-13
  • 2022-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-29
相关资源
最近更新 更多