1

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

//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

我可能在错误的时间应用了这种排序,但是在这里查看了其他类似的示例后,我遇到了麻烦,感谢您的帮助,谢谢!

4

2 回答 2

0

首先,您在那里对单个项目进行排序,您可能想要对实际列表 $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] =>
        )

)
*/
于 2012-04-26T22:15:53.343 回答
0

ksort - “按键对数组进行排序,维护数据相关性的关键。这主要用于关联数组。”

手册

于 2018-03-01T06:57:03.933 回答