usort sorting multiple fields

后端 未结 3 852
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 04:00

Is it possible to use usort to sort multiple fields in a multidimensional array? For example, I want to sort name alphabetically and then from thos

相关标签:
3条回答
  • 2020-12-13 04:40
    usort($arr, function($a, $b)
    {
        $name = strcmp($a['name'], $b['name']);
        if($name === 0)
        {
            return $a['age'] - $b['age'];
        }
        return $name;
    });
    
    0 讨论(0)
  • 2020-12-13 04:49

    How about:

    $arr = Array (
        0 => Array (
            'name' => 'Jonah',
            'age' => '27',
        ),
        1 => Array (
            'name' => 'Bianca',
            'age' => '32',
        ),
        2 => Array (
            'name' => 'Jonah',
            'age' => '25',
        ),
        3 => Array (
            'name' => 'Bianca',
            'age' => '35',
        ),
    );
    function comp($a, $b) {
        if ($a['name'] == $b['name']) {
            return $a['age'] - $b['age'];
        }
        return strcmp($a['name'], $b['name']);
    }
    
    usort($arr, 'comp');
    print_r($arr);
    

    output:

    Array
    (
        [0] => Array
            (
                [name] => Bianca
                [age] => 32
            )
    
        [1] => Array
            (
                [name] => Bianca
                [age] => 35
            )
    
        [2] => Array
            (
                [name] => Jonah
                [age] => 25
            )
    
        [3] => Array
            (
                [name] => Jonah
                [age] => 27
            )
    
    )
    
    0 讨论(0)
  • 2020-12-13 04:53

    How about:

    <?php
    
    function getRandomName() {
        $possible = "ab";
        $possible_len = strlen($possible);
        $r = '';
        for ($i = 0; $i < 4; $i++) {
            $r .=  substr($possible, mt_rand(0, $possible_len-1), 1);
        }
        return ucfirst($r);
    }
    
    $a = array();
    for ($i = 0; $i < 10; $i++) {
        $a[] = array('name' => getRandomName(), 'age' => rand(1,10), 'start_order' => $i);
    }
    $order = array('name' => 'desc', 'age' => 'asc');
    
    print_r($a);
    
    usort($a, function ($a, $b) use ($order) {
        $t = array(true => -1, false => 1);
        $r = true;
        $k = 1;
        foreach ($order as $key => $value) {
            $k = ($value === 'asc') ? 1 : -1;
            $r = ($a[$key] < $b[$key]);
            if ($a[$key] !== $b[$key]) {
                return $t[$r] * $k;
            }
    
        }
        return $t[$r] * $k;
    });
    
    print_r($a);
    
    0 讨论(0)
提交回复
热议问题