简体   繁体   中英

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?

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.

NB: your loop can be replaced with a call to array_column if you are on PHP version >= 5.5.

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);

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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