按值按字母顺序对多维数组进行排序,并将其存储在新变量中

时间:2017-07-27 09:18:56

标签: php arrays sorting multidimensional-array

我有以下数组我想按值排序,A到Z,并存储在 new arary $atoz_people中:

$people = (
 [0] => Array
    (
        [id] => 1
        [name] => Ken
    )

 [1] => Array
    (
        [id] => 2
        [name] => Anne
    )

 [2] => Array
    (
        [id] => 3
        [name] => Bob
    )

);

我使用了" classic" asort($people)

$atoz_people = $people;
asort($atoz_people);
print_r($atoz_people);

不幸的是,它不起作用。为了得到下面的数组我应该改变什么?它甚至可能吗?

$atoz_people = (
    [1] => Array
    (
        [id] => 2
        [name] => Anne
    )
    [2] => Array
    (
        [id] => 3
        [name] => Bob
    )
    [0] => Array
    (
        [id] => 1
        [name] => Ken
    )    

);

2 个答案:

答案 0 :(得分:3)

1)将初始数组存储在一个新变量中:

$atoz_people = $people;

2)创建排序功能:

function sort_by_name($a,$b)
{
    return $a["name"] > $b["name"];
}

3)排序数组

uasort($atoz_people,"sort_by_name");
print_r_html($atoz_people);

@B。德赛:非常感谢!

答案 1 :(得分:0)

对于多维,您可以使用usortuasort

等方法
uasort($people,"sort_name");
var_dump($people);
function sort_name($a,$b)
{
  return $a["name"] > $b["name"];
}

检查link

OR

link