如何通过子数组键和值对数组进行排序

时间:2014-11-09 16:39:51

标签: php arrays sorting

大家好:)这是我的第一个问题,所以我希望能回答:) 我有一个像这样的数组:

Array(
    [] => Array ([category] => 3 )
    [] => Array ([price] => 5 )
    [] => Array ([rating] => 1 )
    [] => Array ([price] => 3 )
    [] => Array ([category] => 1 )
    [] => Array ([category] => 2 )
    )
)

问题:我怎么能为它排序呢。通过子阵列键和子阵列值的字母数字,以便它像下面那样被转换?

Array(
    [] => Array ([category] => 1 )
    [] => Array ([category] => 2 )
    [] => Array ([category] => 3 )
    [] => Array ([price] => 3 )
    [] => Array ([price] => 5 )
    [] => Array ([rating] => 1 )
)

1 个答案:

答案 0 :(得分:2)

您正在寻找array_multisort

$x = Array(
    Array ("category" => 3 ),
    Array ("price" => 5 ),
    Array ("rating" => 1 ),
    Array ("price" => 3 ),
    Array ("category" => 1 ),
    Array ("category" => 2 ),

);

array_multisort(
    array_map('key', $x), 
    array_map('current', $x), 
    $x);

print_r($x);