PHP按几个标准排序数组

时间:2017-03-27 00:13:40

标签: php arrays multidimensional-array

我使用PHP编写并具有多维数组。我想对我的数组进行排序。最重要的标准是总分。第二个标准是名称。

换句话说,数组应按这样排序:

第1个[info] [total],降序

第二个[info] [name],升序

Array (
  [183] => Array (
    [3] => Array (
      [1] => Array ()
    )

    [1] => Array (
      [8] => Array ()
    )

    [info] => Array (
      [name] => Doe John /* 2nd criteria */
      [total] => 4800 /* 1st criteria */
    )
  )

  [380] => Array (
    [4] => Array (
      [6] => Array ()
    )

    [info] => Array (
      [name] => Davis Ben /* 2nd criteria */
      [total] => 14500 /* 1st criteria */
    )

    [2] => Array (
      [5] => Array ()
    )
  )
)

所以,结果应该是这样的:

Array (
  [380] => Array (
    [4] => Array (
      [6] => Array ()
    )

    [info] => Array (
      [name] => Davis Ben
      [total] => 14500
    )

    [2] => Array (
      [5] => Array ()
    )
  )

  [183] => Array (
    [3] => Array (
      [1] => Array ()
    )

    [1] => Array (
      [8] => Array ()
    )

    [info] => Array (
      [name] => Doe John
      [total] => 4800
    )
  )
)

我试过这个:

foreach ($array as &$item)
{
  uasort($item, function ($a, $b)
  {
    if ($a['total'] == $b['total']
    {
      return $b['name'] - $a['name'];
    }
    else
    {
      return $b['total'] - $a['total'];
    }
  }); 
}

我也尝试了这个,但它没有帮助:

foreach ($array as &$item)
{
  uasort($item, function ($a, $b)
  {
    if ($a['info']['total'] == $b['info']['total'])
    {
      return $b['info']['name'] - $a['info']['name'];
    }
    else
    {
      return $b['info']['total'] - $a['info']['total'];
    }
  });
}

1 个答案:

答案 0 :(得分:0)

您的问题请求(按自定义条件排序值,保持键和值之间的关联)与PHP函数uasort()的描述完全匹配。

代码是这样的:

$input = Array(
    '183' => Array(
        '3' => Array(
            '1' => Array(),
        ),
        '1' => Array(
            '8' => Array(),
        ),
        'info' => Array(
            'name'  => 'Doe John',      /* 2nd criteria */
            'total' => 4800,            /* 1st criteria */
        ),
    ),
    '380' => Array(
        '4' => Array(
            '6' => Array(),
        ),
        'info' => Array(
            'name'  => 'Davis Ben',     /* 2nd criteria */
            'total' => 14500,           /* 1st criteria */
        ),
        '2' => Array(
            '5' => Array(),
        ),
    ),
);

uasort($input, function (array $a, array $b) {
    // compare using the 1st criterion
    if ($a['info']['total'] != $b['info']['total']) {
        return $b['info']['total'] - $a['info']['total'];       // < 0 when $a > $b (descending)
    }

    // equality on the 1st criterion, use the 2nd one
    return strcmp($a['info']['name'], $b['info']['name']);      // < 0 when $a < $b (ascending)
});