基于键对多维数组进行排序

时间:2012-07-18 12:47:53

标签: php arrays sorting

我试图根据多维数组中的特定键值对数组进行排序,如下所示

<?php
$country = array(
    array(
        'country' => 'India',
        'visits' => 22,
        'newVisits' => 16,
        'newVisitsPercent' => 72.7),
    array(
        'country' => 'USA',
        'visits' => 30,
        'newVisits' => 15,
        'newVisitsPercent' => 50),
    array(
        'country' => 'Japan',
        'visits' => 25,
        'newVisits' => 15,
        'newVisitsPercent' => 60));
?>

我想按照数组的“访问”键的降序对数组进行排序。

所需数组

<?php
$country = array(
    array(
        'country' => 'USA',
        'visits' => 30,
        'newVisits' => 15,
        'newVisitsPercent' => 50),
    array(
        'country' => 'Japan',
        'visits' => 25,
        'newVisits' => 15,
        'newVisitsPercent' => 60),
    array(
        'country' => 'India',
        'visits' => 22,
        'newVisits' => 16,
        'newVisitsPercent' => 72.7));
?>

尝试在SO中搜索所有结果都是根据键的值进行排序。请告诉我们我们需要使用哪种功能。

我查看了ksort,多重排序函数

2 个答案:

答案 0 :(得分:4)

答案 1 :(得分:4)

PHP有一个名为usort()的内置函数,可以对这些类型的数组进行排序。

您的比较功能可能如下所示:

function mycmp($a, $b) {
  return intval($a['visits']) - intval($b['visits']);
}