排序多个字段

2021/01/15 15:41 · php ·  · 0评论

是否可以用于usort对多维数组中的多个字段进行排序?例如,我想name按字母顺序排序,然后从这些记录中按排序age这可能使用sort吗?

Array ( 
    [0] => Array ( 
        [name] => Jonah 
        [age] => 27 
    )
    [1] => Array (
        [name] => Bianca 
        [age] => 32 
    )
)

怎么样:

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

输出:

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
        )

)
usort($arr, function($a, $b)
{
    $name = strcmp($a['name'], $b['name']);
    if($name === 0)
    {
        return $a['age'] - $b['age'];
    }
    return $name;
});

怎么样:

<?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);
本文地址:http://php.askforanswer.com/paixuduogeziduan.html
文章标签: ,   ,   ,  
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!