我有一个类似下面提到的数组
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降序排序
因此订单将是:办公产品,附加软件,硬件部件
有没有需要帮助的人
发布于 2011-06-30 14:23:25
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"];'));发布于 2011-06-30 14:17:48
使用自定义函数和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)值。
发布于 2011-06-30 14:30:10
下面是可以用来进行多维排序的类
注意:您必须有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);干杯!也许这对你有帮助
https://stackoverflow.com/questions/6530631
复制相似问题