本文介绍了php-usort或array_multisort?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试按升序对下面的数组进行排序,我有点困惑,哪种更好使用... usort或array_multisort?我在想usort,因为它是多维的?有人有这样的例子吗?

Trying to sort the array below by memnum in ascending order, and I'm a bit confused which is better to use... usort or array_multisort? I was thinking usort because it's multidimensional? Does anyone have an example of this?

Array
(
    [0] => Array
        (
            [memnum] => 3236467423
            [mid] => 1104881300  
            [fname] => JOHN        
            [lname] => DOE                 
            [add1] =>  OMITTED
            [add2] =>             
            [city] => CHESTERFIELD      
            [state] => MI
            [zip] => 48051
            [age] => 50 
        )
    [1] => Array
        (
            [memnum] => 3258467922
            [mid] => 1105121457  
            [fname] => JANE        
            [lname] => DOE                 
            [add1] =>  OMITTED
            [add2] =>             
            [city] => CHESTERFIELD      
            [state] => MI
            [zip] => 48051
            [age] => 50 
        )
    [2] => Array
        (
            [memnum] => 3237769108
            [mid] => 1104489312  
            [fname] => BOB        
            [lname] => DOE                 
            [add1] =>  OMITTED
            [add2] =>             
            [city] => CHESTERFIELD      
            [state] => MI
            [zip] => 48051
            [age] => 50 
        )
)

推荐答案

只需 usort :

usort($arr, function (array $a, array $b) { return $a["memnum"] - $b["memnum"]; });

array_multisort 用于同时比较来自不同数组(或子数组)的元素.您只想比较一个数组的元素,因此使用usort.这些元素本身就是数组这一事实是无关紧要的.

array_multisort is used to compare elements from different arrays (or sub-arrays) at the same time. You want to compare elements of only one array, so you use usort. The fact that those elements are themselves arrays is irrelevant.

这篇关于php-usort或array_multisort?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 10:06