简体   繁体   English

按值按字母顺序对多维数组排序(当前第一行除外)

[英]Sort Multidimensional Array by Value Alphabetically, Except for the Current First Row

I've got a multidimensional array that I want to sort alphabetically by the "label" value except for the current first row (skip the first row, alphabetize the other rows). 我有一个多维数组,除了当前的第一行 (跳过第一行,按字母顺序排列其他行),我想 “标签”值按字母顺序排序。

Current Code: 当前代码:

        foreach ($values as $key => $row) {
            $val[$key]  = $row['label'];
        }
        array_multisort($val, SORT_ASC, $values);

Example of Array: 数组示例:

id    label
 0    blue
 1    orange
 2    red
 3    yellow
 4    green
 5    violet
 6    black

The current code is sorting everything. 当前代码正在对所有内容进行排序。 Would I need to split them into 2 arrays, sort, then join them or is there an easier way? 我需要将它们分成2个数组,进行排序,然后将它们加入,还是有更简单的方法?

The end result should look like this: 最终结果应如下所示:

id    label
 0    blue
 6    black
 4    green
 1    orange
 2    red
 5    violet
 3    yellow

You could just do: 您可以这样做:

$val[0] = ""; // fix first row

... before applying the sort. ...在应用排序之前。 So you just replace the first label with an empty string, which will be sorted to first position. 因此,只需将第一个标签替换为空字符串,该字符串将被排序到第一个位置。 Note that these labels were copies, so this manipulation does not affect your 2D array. 请注意,这些标签是副本,因此此操作不会影响您的2D阵列。

NB: your loop can be replaced with a call to array_column if you are on PHP version >= 5.5. 注意:如果您使用的PHP版本> = 5.5,则可以使用对array_column的调用来替换循环。

So the script then becomes: 因此,脚本将变为:

$val = array_column($values, 'label');
$val[0] = ""; // fix first row
array_multisort($val, SORT_ASC, $values);

I really suggest you use objects that you then sort. 我真的建议您使用随后进行排序的对象。 You can push these into an array so you have an array of sorted objects by the end of it. 您可以将它们压入一个数组,以便在其末尾有一个排序对象数组。

<?php
// This is a fake array below that you would replace
$values = ['blue', 'green', 'yellow', 'gray'];
// Array of objects
$object_array = [];
foreach ($values as $key => $row) {
    $item = (object) [
    'id' => $key,
    'label' => $row,
    ];
    $object_array[] = $item;
}
// Create the custom sort function
function sort_labels($a, $b) {
  return strcmp($a->label, $b->label);
}
// Call the custom sort function using usort
usort($object_array, "sort_labels");

// Prints out the sorted object array
print_r($object_array);

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM