Interview - a written test question on php array sorting
世界只因有你
世界只因有你 2017-05-16 13:00:16
0
5
723

Array:

$array = [
            0=>"z01",
            1=>"Z32",
            2=>"z17",
            3=>"Z16",
        ];

Need sorted results

$rs_array = [
        0=>"z01",
        3=>"Z16",
        2=>"z17",
        1=>"Z32",
    ];

What’s a good way to sort?

世界只因有你
世界只因有你

reply all(5)
某草草
asort($array, SORT_FLAG_CASE | SORT_NATURAL);
var_dump($array);

Get:

array:4 [
  0 => "z01"
  3 => "Z16"
  2 => "z17"
  1 => "Z32"
]
PHPzhong

You can use user-defined comparison function, usort.


$array  = [
            0=>"z01",
            1=>"Z32",
            2=>"z17",
            3=>"Z16",
        ];

function cmp($a,$b){
  $a = intval(substr($a, 1));
  $b = intval(substr($b, 1));
  if ($a == $b) {
    return 0;
  }
  return ($a < $b ) ? -1 : 1;
}

usort($array, "cmp");
print_r($array);

/*

Array
(
    [0] => z01
    [1] => Z16
    [2] => z17
    [3] => Z32
)

 */
phpcn_u1582

One system function to do it

<?php
$array  = [
            0=>"z01",
            1=>"Z32",
            2=>"z17",
            3=>"Z16",
        ];
natcasesort($array);
print_r($array);
阿神

There is an array function that directly compares values

世界只因有你

array_sort(array_values($rs_array))

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template