使用CaseInSensitive对Asc中的数组排序

时间:2015-12-16 12:03:40

标签: php arrays sorting

我正在尝试使用键对以下数组进行排序 - " name"除了casesensitive,任何人都可以帮助我吗?

$result = array(
    array("name" => "Vino", "age" => 25),
    array("name" => "bino", "age" => 25),
    array("name" => "", "age" => 25)
    array("name" => "Jino", "age" => 25),
    array("name" => "Mino", "age" => 25)
) 

因此输出数组应如下所示,

    array(
        array("name" => "bino", "age" => 25),
        array("name" => "Jino", "age" => 25),
        array("name" => "Mino", "age" => 25),
        array("name" => "Vino", "age" => 25)
        array("name" => "", "age" => 25)
    )

2 个答案:

答案 0 :(得分:1)

您可以尝试这样array_multisort

注意:标记SORT_NATURAL & SORT_FLAG_CASE用于使其caseinsensitive

   <?php 

$result = array(
        array("name" => "Vino", "age" => 25),
        array("name" => "bino", "age" => 25),
        array("name" => "", "age" => 25),
        array("name" => "Jino", "age" => 25),
        array("name" => "Mino", "age" => 25)
);

$orderKey=array();
foreach($result as $key=>$data){
    $orderKey[$key]=$data['name'];
}
array_multisort($orderKey, SORT_ASC|SORT_NATURAL|SORT_FLAG_CASE, $result);
echo "<pre>";
print_r($result);
?>

<强>输出:

Array (
    [0] => Array
        (
            [name] => 
            [age] => 25
        )

    [1] => Array
        (
            [name] => bino
            [age] => 25
        )

    [2] => Array
        (
            [name] => Jino
            [age] => 25
        )

    [3] => Array
        (
            [name] => Mino
            [age] => 25
        )

    [4] => Array
        (
            [name] => Vino
            [age] => 25
        )

)

答案 1 :(得分:0)

可以这样做:

$result = array(
   array("name" => "Vino", "age" => 25),
   array("name" => "bino", "age" => 25),
   array("name" => "", "age" => 25),
   array("name" => "Jino", "age" => 25),
   array("name" => "Mino", "age" => 25)
) 

usort($result, function($a, $b) {
    return strcasecmp($a["name"], $b["name"]);
});

<强>输出:

Array
(
    [0] => Array
        (
            [name] => 
            [age] => 25
        )

    [1] => Array
        (
            [name] => bino
            [age] => 25
        )

    [2] => Array
        (
            [name] => Jino
            [age] => 25
        )

    [3] => Array
        (
            [name] => Mino
            [age] => 25
        )

    [4] => Array
        (
            [name] => Vino
            [age] => 25
        )

)