给定这个数组:

$inventory = array(

   array("type"=>"fruit", "price"=>3.50),
   array("type"=>"milk", "price"=>2.90),
   array("type"=>"pork", "price"=>5.43),

);

我想按价格排序$inventory的元素,以获得:

$inventory = array(

   array("type"=>"pork", "price"=>5.43),
   array("type"=>"fruit", "price"=>3.50),
   array("type"=>"milk", "price"=>2.90),

);

我该怎么做呢?


当前回答

试试这个:

$prices = array_column($inventory, 'price');
array_multisort($prices, SORT_DESC, $inventory);
print_r($inventory);

其他回答

许多人都在寻找一种方法来做Laravel,并最终在这里结束。此外,一些Laravel问题由于这个问题的重复而被关闭。 因此,我分享了一种使用Laravel collect()方法执行它的简单方法。

$inventory = collect($inventory)->sortBy('price')->toArray();

降序排列

$inventory = collect($inventory)->sortBy('price')->reverse()->toArray();

Or,

$inventory = collect($inventory)->('price')->reverse()->toArray();
//Just in one line custom function
function cmp($a, $b)
{
return (float) $a['price'] < (float)$b['price'];
}
@uasort($inventory, "cmp");
print_r($inventory);

//result

Array
(
[2] => Array
    (
        [type] => pork
        [price] => 5.43
    )

[0] => Array
    (
        [type] => fruit
        [price] => 3.5
    )

[1] => Array
    (
        [type] => milk
        [price] => 2.9
    )

)

你可以将usort与匿名函数一起使用,例如:

usort($inventory, function ($a, $b) { return strnatcmp($a['price'], $b['price']); });

我的结尾是这样的:

function sort_array_of_array(&$array, $subfield)
{
    $sortarray = array();
    foreach ($array as $key => $row)
    {
        $sortarray[$key] = $row[$subfield];
    }

    array_multisort($sortarray, SORT_ASC, $array);
}

只需调用函数,传递数组和第二级数组字段的名称。 如:

sort_array_of_array($inventory, 'price');

你是对的,你要找的函数是array_multisort()。

下面是一个直接摘自手册并根据你的情况进行调整的例子:

$price = array();
foreach ($inventory as $key => $row)
{
    $price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);

从PHP 5.5.0开始,你可以使用array_column()来代替foreach:

$price = array_column($inventory, 'price');

array_multisort($price, SORT_DESC, $inventory);