使用第二个元素进行分类
asort using the second element
从这个数组开始:
$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_multisorthttp://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]);
从这个数组开始:
$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_multisorthttp://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]);