按键按字母顺序对多维数组进行排序


Sorting multidimensional array by key alphabetically

尝试按屏幕名称按此多维数组排序:

//Looping through this for each member of a group
unset($member_info);
$member_info->id           =   $member->id;
$member_info->screen_name  =   $member->screen_name;
$member_info->first_name   =   $member->first_name;
$member_info->last_name    =   $member->last_name;
$member_info->email        =   $member->email;
//Sort member_info by screen name
$member_array = sort_by_array_key($member_info,$member_info->screen_name,'ASC');
$member_list[] = $member_array;

排序功能:

function sort_by_array_key($array,$sort_key,$dir = 'ASC') {
    usort($array, function($a,$b) use ($sort_key){
        return strnatcasecmp($a["$sort_key"], $b["$sort_key"]);
    });
    if ( $dir == 'DESC' ) { return array_reverse($array); }
    else { return $array; }
}

例如,即使在我运行排序函数之后,屏幕名称当前仍按此顺序排列:

newUser
Chris
Carlos
Jason

可能在错误的时间应用了排序,但是在这里查看了其他类似示例后,我遇到了麻烦,任何帮助都值得赞赏,谢谢!

首先,您在那里对单个项目进行排序,您可能希望对实际列表 $member_list 进行排序。此外,您正在尝试对初始化对象的数组进行排序。初始化数组或对对象进行排序。

如果我假设你真的想玩数组,就像你在这个问题上暗示的那样,这可能是你正在尝试做的事情:

<?php
$member_info = Array();
$member_info['id']           =   '1';
$member_info['screen_name']  =   'Chris';
$member_info['first_name']   =   '';
$member_info['last_name']    =   '';
$member_info['email']        =   '';
$member_list[] = $member_info;
$member_info = Array();
$member_info['id']           =   '2';
$member_info['screen_name']  =   'Carlos';
$member_info['first_name']   =   '';
$member_info['last_name']    =   '';
$member_info['email']        =   '';
$member_list[] = $member_info;
$member_info = Array();
$member_info['id']           =   '3';
$member_info['screen_name']  =   'Jason';
$member_info['first_name']   =   '';
$member_info['last_name']    =   '';
$member_info['email']        =   '';
$member_list[] = $member_info;

//Sort member_list by screen name
$member_list = sort_by_array_key($member_list,'screen_name','ASC');
function sort_by_array_key($array,$sort_key,$dir = 'ASC') {
    usort($array, function($a,$b) use ($sort_key){
        return strnatcasecmp($a["$sort_key"], $b["$sort_key"]);
    });
    if ( $dir == 'DESC' ) { return array_reverse($array); }
    else { return $array; }
}
print_r($member_list);
/*
Array
(
    [0] => Array
        (
            [id] => 2
            [screen_name] => Carlos
            [first_name] =>
            [last_name] =>
            [email] =>
        )
    [1] => Array
        (
            [id] => 1
            [screen_name] => Chris
            [first_name] =>
            [last_name] =>
            [email] =>
        )
    [2] => Array
        (
            [id] => 3
            [screen_name] => Jason
            [first_name] =>
            [last_name] =>
            [email] =>
        )
)
*/

ksort - "按键对数组进行排序,保持键到数据相关性。这主要对关联数组有用。

查看手册