我在 PHP 中有这个数组:
在 PHP API 中,我有这个数组,想按 custom_price 排序,但不知道如何实现..
Array
(
[0] => Array
(
[id] => 1204
[custom_price] => 33.1500
)
[1] => Array
(
[id] => 1199
[custom_price] => 16.83
)
[2] => Array
(
[id] => 1176
[custom_price] => 16.83
)
[3] => Array
(
[id] => 1173
[custom_price] => 11.73
)
[4] => Array
(
[id] => 1170
[custom_price] => 22.5
)
)
我如何按自定义价格从..高到低和从低到高排序
使用
usort
:
从高到低
usort($input, function ($a, $b) {return $a['custom_price'] < $b['custom_price'];});
print_r( $input );
从低到高
usort($input, function ($a, $b) {return $a['custom_price'] > $b['custom_price'];});
print_r( $input );
http://php.net/manual/en/function.usort.php
请记住,这在 8+ 中已弃用,必须返回 Int 值
使用
usort
:
字符串比较:
参考这个Stackoverflow答案
综合比较
降序
usort($sidebarData ->rankingData, function ($a, $b) {
if ($a->integerProperty == $b->intergerProperty)
{
return 0;
}
return ($a->integerProperty < $b->integerProperty) ? 1 : -1;});
上升
usort($sidebarData ->rankingData, function ($a, $b) {
if ($a->integerProperty == $b->intergerProperty)
{
return 0;
}
return ($a->integerProperty < $b->integerProperty) ? -1 : 1;});
这个解决方案可能对您有帮助。
function sortByOrder($a, $b) {
return $a['custom_price'] - $b['custom_price'];
}
usort($myArray, 'sortByOrder');
或者
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
}
aasort($your_array,"custom_price");
这里是参考链接
将
与array_multisort()
和SORT_DESC
一起使用SORT_ASC
<?php
$MYarray=
array(
0 => array(
"id"=> 1204,
"custom_price"=> 33.1500
),
1 => array(
"id"=> 1199,
"custom_price"=> 16.83
),
2 => array(
"id"=> 1176,
"custom_price"=> 316.83
));
$custom_price = array();
foreach ($MYarray as $key => $row)
{
$custom_price[$key] = $row['custom_price'];
}
array_multisort($custom_price, SORT_DESC, $MYarray);
var_dump($MYarray);
?>
使用 Ksort
$age=array("1204"=>"33.1500","1199"=>"16.83","1176"=>"11.73");
ksort($age);
foreach($age as $x=>$x_value)
{
echo "Value=" . $x_value;
echo "<br>";
}
输出
Value=11.73
Value=16.83
Value=33.1500
提示: 使用 krsort() 函数根据键对关联数组进行降序排序。
提示: 使用 asort() 函数根据值对关联数组进行升序排序。
// Descending order
function sortByDecOrder($a, $b) {
return $b['custom_price'] - $a['custom_price'];
}
usort($arr, 'sortByOrder');
// Ascending order
function sortByAscOrder($a, $b) {
return $b['custom_price'] - $a['custom_price'];
}
usort($arr, 'sortByOrder');
您可以使用
usort
功能
<?php
$array = array(
"0" => array (
"id" => 1204,
"custom_price" => 33.1500
),
"1" => array (
"id" => 1199,
"custom_price" => 20.83
),
"2" => array (
"id" => 1176,
"custom_price" => 19.83
)
);
usort($array, function($a, $b) {
return $a['custom_price'] - $b['custom_price'];
});
echo "<pre>";
print_r($array);