猿问

基于键对PHP多维数组进行排序?

我正在尝试根据特定键对PHP哈希表进行排序。数据结构如下所示:


print_r($mydata);


Array(

[0] => Array

    (

        [type] => suite

        [name] => A-Name

    )

[1] => Array

    (

        [type] => suite

        [name] => C-Name

    )

[2] => Array

    (

        [type] => suite

        [name] => B-Name

    )

)

我已经尝试过ksort,sort,usort,但是似乎没有任何作用。我正在尝试根据名称键向下两级进行排序。


这是我尝试使用usort的尝试:


function cmp($a, $b) {

    return $b['name'] - $a['name'];

}


usort($mydata, "cmp");

有没有简单的方法可以做到这一点,或者我需要编写一个自定义排序功能?


墨色风雨
浏览 501回答 3
3回答

慕码人8056858

试试这个usort函数:&nbsp; &nbsp; function cmp($a, $b){&nbsp; &nbsp; &nbsp; &nbsp; if ($a == $b)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 0;&nbsp; &nbsp; &nbsp; &nbsp; return ($a['name'] < $b['name']) ? -1 : 1;&nbsp; &nbsp; }$my_array = array(0 => array&nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; 'type' => 'suite'&nbsp; &nbsp; &nbsp; &nbsp; ,'name' => 'A-Name'&nbsp; &nbsp; ),1 => array&nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; 'type' => 'suite'&nbsp; &nbsp; &nbsp; &nbsp; ,'name' => 'C-Name'&nbsp; &nbsp; ),2 => array&nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; 'type' => 'suite'&nbsp; &nbsp; &nbsp; &nbsp; ,'name' => 'B-Name'&nbsp; &nbsp; ));usort($my_array, "cmp");如果在类中使用它,则第二个参数将更改为如下数组:usort($my_array, array($this,'cmp'));

智慧大石

&nbsp;<?php$a=array(array('a'=>5,'b'=>7),array('c'=>4,'d'=>2),array('e'=>0,'f'=>12)&nbsp; &nbsp; );function cmp_sort($x,$y){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//your function to compare two keysif($x===$y)&nbsp; &nbsp; return 0;else&nbsp; &nbsp; return ($x<$y?1:-1);}uasort($a,'cmp_sort');&nbsp; &nbsp; //call user-defined compare functionprint_r($a);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //printing the sorted array?>输出=>数组([2] =>数组([e] => 0 [f] => 12)[1] =>数组([c] => 4 [d] => 2)[0] =>数组([ a] => 5 [b] => 7))
随时随地看视频慕课网APP
我要回答