asort使用第二个元素



从这个数组开始:

$TEST=array (
0 => array ( 0 => 'b', 1 => 'y', 2 => 'O', ),
1 => array ( 0 => 'a', 1 => 'z', 2 => 'O', ),
2 => array ( 0 => 'c', 1 => 'x', 2 => 'O', ),
)

如何排序?(xyz基于第二个元素(:

$TEST=array (
2 => array ( 0 => 'c', 1 => 'x', 2 => 'O', ),
0 => array ( 0 => 'b', 1 => 'y', 2 => 'O', ),
1 => array ( 0 => 'a', 1 => 'z', 2 => 'O', ),
)

简单asort($TEST)的结果是(abc基于第一个元素(:

$TEST=array (
1 => array ( 0 => 'a', 1 => 'z', 2 => 'O', ),
0 => array ( 0 => 'b', 1 => 'y', 2 => 'O', ),
2 => array ( 0 => 'c', 1 => 'x', 2 => 'O', ),
)

您可以使用以下一行代码:

array_multisort( array_column($yourArray, $index), SORT_ASC, $yourArray );

在您的情况下,以下是如何使用它:

$TEST=array (
0 => array ( 0 => 'b', 1 => 'y', 2 => 'O', ),
1 => array ( 0 => 'a', 1 => 'z', 2 => 'O', ),
2 => array ( 0 => 'c', 1 => 'x', 2 => 'O', ),
)
array_multisort( array_column($TEST, 1), SORT_ASC, $TEST );
print_r($TEST);

在此处检查array_multi-sorthttp://php.net/manual/en/function.array-multisort.php

与宇宙飞船的显式uasort:

<?php
$items = [
0 => [ 0 => 'b', 1 => 'y', 2 => 'O' ],
2 => [ 0 => 'c', 1 => 'x', 2 => 'O' ],
1 => [ 0 => 'a', 1 => 'z', 2 => 'O' ]
];
uasort($items, function($a, $b) { return $a[1] <=> $b[1]; });
var_export($items);

输出:

array (
2 => 
array (
0 => 'c',
1 => 'x',
2 => 'O',
),
0 => 
array (
0 => 'b',
1 => 'y',
2 => 'O',
),
1 => 
array (
0 => 'a',
1 => 'z',
2 => 'O',
),
)

用短箭头函数表示法书写:

uasort($items, fn($a, $b) => $a[1] <=> $b[1]);

相关内容

  • 没有找到相关文章

最新更新