如何根据特定值控制此多维数组的顺序?

时间:2014-06-26 15:26:03

标签: php arrays multidimensional-array asort

在阅读了有关此主题的几篇帖子后,我无法找到问题的确切答案。

我当前的数组是:

Array
(
    [0] => Array
        (
            [Level] => Bronze
            [Name] => JP Morgan
            [Logo] => Logo
        )

    [1] => Array
        (
            [Level] => Bronze
            [Name] => NASDAQ OMX
            [Logo] => Logo
        )

    [2] => Array
        (
            [Level] => Platinum
            [Name] => Credit Suisse
            [Logo] => Logo
        )

    [3] => Array
        (
            [Level] => Silver
            [Name] => BNP Paribas
            [Logo] => Logo
        )

)

我想要的是让所有赞助商按[Level]排序,订单是:

  • 青铜

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以定义own sorting function。例如,您可以指定自己要遵循的自定义订单:

$sort_order = array('Platinum', 'Gold', 'Silver', 'Bronze');

将包含所有数据的数组传递到自定义排序功能,然后按照您刚刚定义的排序顺序搜索值的关键位置(在本例中为Level):

$array = array(
  array (
    'Level' => 'Bronze',
      'Name' => 'JP Morgan',
      'Logo' => 'Logo'
  ),
  array (
      'Level' => 'Bronze',
      'Name' => 'NASDAQ OMX',
      'Logo' => 'Logo'
  ),
  array (
      'Level' => 'Platinum',
      'Name' => 'Credit Suisse',
      'Logo' => 'Logo'
  ),
  array (
      'Level' => 'Silver',
      'Name' => 'BNP Paribas',
      'Logo' => 'Logo'
  ),
);

usort($array, function ($a, $b) use ($sort_order) {
    return array_search($a['Level'], $sort_order) - array_search($b['Level'], $sort_order);
});

print_r($array);

输出:

Array
(
[0] => Array
    (
        [Level] => Platinum
        [Name] => Credit Suisse
        [Logo] => Logo
    )

[1] => Array
    (
        [Level] => Silver
        [Name] => BNP Paribas
        [Logo] => Logo
    )

[2] => Array
    (
        [Level] => Bronze
        [Name] => NASDAQ OMX
        [Logo] => Logo
    )

[3] => Array
    (
        [Level] => Bronze
        [Name] => Jp Morgan
        [Logo] => Logo
    )
)