欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

PHP:二维数组根据某个字段排序

程序员文章站 2022-03-01 12:39:44
...
 /**
     * 二维数组根据某个字段排序
     */
    public function sortArr()
    {
        $user_list = [
            ['name' => '张三', 'age' => 28],
            ['name' => '赵六', 'age' => 21],
            ['name' => '王五', 'age' => 20],
            ['name' => '李四', 'age' => 21]
        ];
        //按字段age排序
        array_multisort(array_column($user_list, 'age'),SORT_ASC,$user_list);
        echo "<pre>";
        var_dump($user_list);

        $user_list = [
            ['name' => 'candy', 'age' => 28],
            ['name' => 'ac', 'age' => 21],
            ['name' => 'Bd', 'age' => 18],
            ['name' => 'abby', 'age' => 20],
            ['name' => 'fly', 'age' => 21],
            ['name' => 'Ay', 'age' => 26]
        ];
        //SORT_STRING 按照字符串比较。但是不区分大小写字母排序。所以这里可以先转换为小写
        $user_list_name = array_map("strtolower",array_column($user_list, 'name'));
        array_multisort($user_list_name,SORT_ASC,SORT_STRING,$user_list);
        var_dump($user_list);
    }