现在有这样一个二维数组

$inventory = array(

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

);

我想通过price对这个二维数组排序,以便得到以下结果:

$inventory = array(

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

);

该如何实现呢?

第一种方法:使用php array_multisort()函数。具体代码如何:

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

 

第二种方法:使用usort函数:

升序排序

usort($inventory, function ($item1, $item2) {
    return $item1[\'price\'] <=> $item2[\'price\'];
});

或者降序排序

usort($inventory, function ($item1, $item2) {
    return $item2[\'price\'] <=> $item1[\'price\'];
});

 

第三种方法:自己写一个php函数。

function SortByKeyValue($data, $sortKey, $sort_flags=SORT_ASC)
{
    if (empty($data) or empty($sortKey)) return $data;

    $ordered = array();
    foreach ($data as $key => $value)
        $ordered[$value[$sortKey]] = $value;

    ksort($ordered, $sort_flags);

    return array_values($ordered); *// array_values() added for identical result with multisort*
}
收藏 打印