PHP:我需要按特定键排序数组[duplicate]

pkbketx9  于 2023-01-24  发布在  PHP
关注(0)|答案(3)|浏览(107)
    • 此问题在此处已有答案**:

how to sort a multidemensional array by an inner key(6个答案)
How do I sort a multidimensional array by one of the fields of the inner array in PHP? [duplicate](8个答案)
How do I Sort a Multidimensional Array in PHP [duplicate](10个答案)
2天前关闭。
我有一个这样的数组:

$events = [[
  'col1' => $eventType,
  'col2' => $eventTime,
  'col3' => $eventLocation,
]];
Array (
  [0] => Array (
    [col1] => play
    [col2] => 39
    [col3] => home
  )
  [1] => Array (
    [col1] => card
    [col2] => 16
    [col3] => home
  )
  [2] => Array (
    [col1] => play
    [col2] => 67
    [col3] => home
  )
)

如何按第二列($eventTime)对它们进行排序?正确的顺序应该是[1],[0],[2]。
我尝试了各种排序选项,但不确定如何将col2指定为排序的关键字。

uxhixvfz

uxhixvfz1#

您需要尝试array_multisort()函数。也许您的问题会得到解决。

$col2 = array_column($events, 'col2');
array_multisort($col2, SORT_ASC, $events);

您的数组将如下所示

Array
(
    [0] => Array
        (
            [col1] => card
            [col2] => 16
            [col3] => home
        )

    [1] => Array
        (
            [col1] => play
            [col2] => 39
            [col3] => home
        )

    [2] => Array
        (
            [col1] => playsad
            [col2] => 40
            [col3] => home
        )

)
hmmo2u0o

hmmo2u0o2#

您可以使用array_multisort():

$order_arr = array_column($events, 'col2');
array_multisort($order_arr, SORT_ASC, SORT_NUMERIC /* or other */, $events);

但它不保留密钥:var_export($events)

array (
  0 => 
  array (
    'col1' => 'card',
    'col2' => 16,
    'col3' => 'home',
  ),
  1 => 
  array (
    'col1' => 'play',
    'col2' => 39,
    'col3' => 'home',
  ),
  2 => 
  array (
    'col1' => 'play',
    'col2' => 67,
    'col3' => 'home',
  ),
)

要保留密钥,请参见用户的maSort()函数:var_export(maSort($events, 'col2', 1));

array (
  1 => 
  array (
    'col1' => 'card',
    'col2' => 16,
    'col3' => 'home',
  ),
  0 => 
  array (
    'col1' => 'play',
    'col2' => 39,
    'col3' => 'home',
  ),
  2 => 
  array (
    'col1' => 'play',
    'col2' => 67,
    'col3' => 'home',
  ),
)
wz3gfoph

wz3gfoph3#

可以使用usort()函数对数组进行排序

$array=[...];
usort($array, function ($val1, $val2) {
    return $val2['col2'] < $val1['col2'];
});
var_dump($array);

相关问题