根据特定列对 php 中的多维数组进行排序
sort mulitdimensional array in php according to specific column
我想根据内部数组中的字段对多维数组进行排序,如下所示:
$result = array(
array("first" => 1, "second" => 5),
array("first" => 3, "second" => 8),
array("first" => 6, "second" => 7),
array("first" => 6, "second" => 1)
);
sort($result,"second");
/*
$result = array(
array("first" => 6, "second" => 1),
array("first" => 1, "second" => 5),
array("first" => 6, "second" => 7),
array("first" => 3, "second" => 8)
);
*/
PHP 中是否有类似预期排序功能的东西,或者我是否必须重新实现它?
为此使用usort
This function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.
function cmp($a, $b) {
if ($a['second'] == $b['second']) {
return 0;
}
return ($a['second'] < $b['second']) ? -1 : 1;
}
usort($array, 'cmp');
您甚至可以先排序 'second',然后排序 'first' :)(如果 'second' 相同,则排序 'first')
function cmp($a, $b) {
if ($a['second'] == $b['second']) {
if ($a['first'] == $b['first']) {
return 0;
}
return ($a['first'] < $b['first']) ? -1 : 1;
}
return ($a['second'] < $b['second']) ? -1 : 1;
}
usort($array, "cmp");
这是一个非常简单的数组排序函数。
function sort_by_key($a, $subkey) {
foreach($a as $k=>$v) {
$b[$k] = strtolower($v[$subkey]);
}
asort($b);
foreach($b as $key=>$val) {
$c[] = $a[$key];
}
return $c;
}
你可以这样称呼它:
sort_by_key($result , 'second');
我想根据内部数组中的字段对多维数组进行排序,如下所示:
$result = array(
array("first" => 1, "second" => 5),
array("first" => 3, "second" => 8),
array("first" => 6, "second" => 7),
array("first" => 6, "second" => 1)
);
sort($result,"second");
/*
$result = array(
array("first" => 6, "second" => 1),
array("first" => 1, "second" => 5),
array("first" => 6, "second" => 7),
array("first" => 3, "second" => 8)
);
*/
PHP 中是否有类似预期排序功能的东西,或者我是否必须重新实现它?
为此使用usort
This function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.
function cmp($a, $b) {
if ($a['second'] == $b['second']) {
return 0;
}
return ($a['second'] < $b['second']) ? -1 : 1;
}
usort($array, 'cmp');
您甚至可以先排序 'second',然后排序 'first' :)(如果 'second' 相同,则排序 'first')
function cmp($a, $b) {
if ($a['second'] == $b['second']) {
if ($a['first'] == $b['first']) {
return 0;
}
return ($a['first'] < $b['first']) ? -1 : 1;
}
return ($a['second'] < $b['second']) ? -1 : 1;
}
usort($array, "cmp");
这是一个非常简单的数组排序函数。
function sort_by_key($a, $subkey) {
foreach($a as $k=>$v) {
$b[$k] = strtolower($v[$subkey]);
}
asort($b);
foreach($b as $key=>$val) {
$c[] = $a[$key];
}
return $c;
}
你可以这样称呼它:
sort_by_key($result , 'second');