search

Home  >  Q&A  >  body text

Interview - a written test question on php array sorting

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?

世界只因有你世界只因有你2811 days ago753

reply all(5)I'll reply

  • 某草草

    某草草2017-05-16 13:02:16

    asort($array, SORT_FLAG_CASE | SORT_NATURAL);
    var_dump($array);

    Get:

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

    reply
    0
  • PHPz

    PHPz2017-05-16 13:02:16

    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
    )
    
     */
    

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-16 13:02:16

    One system function to do it

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

    reply
    0
  • 阿神

    阿神2017-05-16 13:02:16

    There is an array function that directly compares values

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-16 13:02:16

    array_sort(array_values($rs_array))

    reply
    0
  • Cancelreply