如果您知道数组的深度,您可以简单地对每个要排序的数组元素应用usort 。
这是一个根据自定义数组排序的示例:
<?php
$order = array(
'first',
'second',
'third',
'fourth',
'fifth'
);
$array = array(
array(
'second',
'fourth',
'first',
'third'
),
array(
'second',
'first'
)
);
foreach($array as &$value) {
usort($value, function($a, $b) use($order) {
return array_search($a, $order) > array_search($b, $order);
});
}
unset($value);
var_dump($array);
/*
array(2) {
[0]=>
array(4) {
[0]=>
string(5) "first"
[1]=>
string(6) "second"
[2]=>
string(5) "third"
[3]=>
string(6) "fourth"
}
[1]=>
array(2) {
[0]=>
string(5) "first"
[1]=>
string(6) "second"
}
}
*/
如果您不知道数组可以走多深,我想到的唯一解决方案是递归函数:
<?php
$order = array(
'first',
'second',
'third',
'fourth',
'fifth'
);
$array = array(
array(
'second',
'fourth',
'first',
'third'
),
array(
array('second', 'first'),
array('fourth', 'third')
)
);
function custom_multisort($array, $order) {
foreach($array as &$value) {
if(is_array($value[0])) {
$value = custom_multisort($value, $order);
} else {
usort($value, function($a, $b) use($order) {
return array_search($a, $order) > array_search($b, $order);
});
}
}
return $array;
}
$array = custom_multisort($array, $order);
var_dump($array);
/*
array(2) {
[0]=>
array(4) {
[0]=>
string(5) "first"
[1]=>
string(6) "second"
[2]=>
string(5) "third"
[3]=>
string(6) "fourth"
}
[1]=>
array(2) {
[0]=>
array(2) {
[0]=>
string(5) "first"
[1]=>
string(6) "second"
}
[1]=>
array(2) {
[0]=>
string(5) "third"
[1]=>
string(6) "fourth"
}
}
}
*/