我有一个像下面提到的数组
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
所以订单将是:办公用品,附加产品,硬件零件
任何帮助人员
答案 0 :(得分:15)
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 :(得分: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
$s = new MultiDimensionSort('total_sales', MultiDimensionSort::DESCENDING); // sort by total_sales
usort($summary, array($s, 'cmp'));
print"<pre>";print_r($summary);
干杯! 可能会帮助你
答案 2 :(得分: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)
值。