douwen3362
2014-01-26 16:19
浏览 83
已采纳

按名称对数组中的数组进行排序

Input:

$sql = array(

    array("id"=>"47", "name"=>"Jason", "device"=>"idevice"),
    array("id"=>"49", "name"=>"uniKornn", "device"=>"idevice"),
    array("id"=>"50", "name"=>"jacob", "device"=>"idevice")
)

Output:

$sql = array(

    array("id"=>"50", "name"=>"jacob", "device"=>"idevice"),
    array("id"=>"47", "name"=>"Jason", "device"=>"idevice"),
    array("id"=>"49", "name"=>"uniKornn", "device"=>"idevice")
)

I want to set the order of the array $sql, by name, and case-insensitive.

图片转代码服务由CSDN问答提供 功能建议

输入:

  $ sql = array(
 
  n array(“id”=>“47”,“name”=>“Jason”,“device”=>“idevice”),
 array(“id”=>“49”,“name”  “=>”uniKornn“,”device“=>”idevice“),
 array(”id“=>”50“,”name“=>”jacob“,”device“=>”  idevice“)
)
   
 
 

输出:

  $ sql = array(
 
 array(
)  “id”=>“50”,“name”=>“jacob”,“device”=>“idevice”),
 array(“id”=>“47”,“name”=>  ;“Jason”,“device”=>“idevice”),
 array(“id”=>“49”,“name”=>“uniKornn”,“device”=>“idevice”)  
)
   
 
 

我想按名称设置数组$ sql的顺序,不区分大小写。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douwei8672 2014-01-26 16:22
    已采纳
    function build_sorter($key) {
        return function ($a, $b) use ($key) {
            return strnatcmp($a[$key], $b[$key]);
        };
    }
    
    usort($sql, build_sorter('name'));
    

    EDIT: For case-insensitive:

    Option 1:

    function build_sorter($key) {
        return function ($a, $b) use ($key) {
            return strnatcasecmp($a[$key], $b[$key]);
        };
    }
    
    usort($sql, build_sorter('name'));
    

    Option 2:

    function build_sorter($key) {
        return function ($a, $b) use ($key) {
            return strnatcmp(strtolower($a[$key]), strtolower($b[$key]));
        };
    }
    
    usort($sql, build_sorter('name'));
    

    Full Code:

    <?php
    
    $sql = array(
        array("id"=>"47", "name"=>"Jason", "device"=>"idevice"),
        array("id"=>"49", "name"=>"uniKornn", "device"=>"idevice"),
        array("id"=>"50", "name"=>"jacob", "device"=>"idevice")
    );
    
    function build_sorter($key) {
        return function ($a, $b) use ($key) {
            return strnatcmp(strtolower($a[$key]), strtolower($b[$key]));
        };
    }
    
    usort($sql, build_sorter('name'));
    
    foreach ($sql as $item) {
        echo $item['id'] . ', ' . $item['name'] .', ' . $item['device'] . "
    ";
    }
    
    ?>
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题