PHP usort:使用单个函数按两个键排序

时间:2017-01-24 11:59:23

标签: php usort

我有下一个数组:

add

我需要根据具体情况按键Array ( [0] => Array ( [name] => 'Paul' [value_1] => 3 [value_2] => 2 ) [1] => Array ( [name] => 'John' [value_1] => 6 [value_2] => 5 ) [2] => Array ( [name] => 'Steve' [value_1] => 1 [value_2] => 9 ) [3] => Array ( [name] => 'Joe' [value_1] => 8 [value_2] => 1 ) ) value_1对数组进行排序。

我这样做:

value_2

可以在单一功能中统一吗?像这样:

<?php

$i = 1;    
usort($my_array, 'sortByOrder_'.$i);

$i = 2;    
usort($my_array, 'sortByOrder_'.$i);

function sortByOrder_1($a, $b) {        
    if ($a['value_1'] < $b['value_1'])
        return 1;          
}

function sortByOrder_2($a, $b) {    
     if ($a['value_2'] < $b['value_2'])
        return 1;        
}

?>

1 个答案:

答案 0 :(得分:1)

您可以使用类似工厂的东西,例如:

type obj
  real :: a
  integer :: n = 1
  real, pointer :: p => null()
  integer, allocatable :: ia
end type


type(obj) :: o
real, target :: pi = 3.14

o = obj(1.0)

o = obj(1.0, 2)

o = obj(1.0, p = pi)

o = obj(1.0, ia = 4)