如何根据一个特定的值来控制这个多维数组的顺序



在阅读了这里关于这个主题的几篇文章之后,我无法找到我问题的确切答案。

我的当前数组是:

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]排序,顺序是:

  • 黄金
  • 青铜

我该怎么做?

您可以定义自己的排序函数。例如,您可以指定您希望它遵循的自定义顺序:

$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
    )
)

相关内容

  • 没有找到相关文章

最新更新