[英]How to sort an array based on the values of another (partial) array in PHP?
How to sort an array based on the values of another (partial) array in PHP?如何根据 PHP 中另一个(部分)数组的值对数组进行排序? Ie
$toBeSorted
is the target array, $sortByThis
provides the keys (not all keys!):即
$toBeSorted
是目标数组, $sortByThis
提供键(不是所有键!):
// Array to be sorted (mantaining key-values correlations)
$toBeSorted = array(
'id' => 'Identifier',
'username' => 'Username',
'phone' => 'Phone number',
'email' => 'E-mail',
);
$sortByThis = array('username', 'id');
// Result should be username, id, email, phone
// The remaining portion of array should be sorted with ksort()
I remember (but I'm not 100% sure) a function to quickly do this.我记得(但我不是 100% 确定)一个可以快速执行此操作的函数。 Actually I've used:
其实我用过:
// Sort the first portion of the array
$sorted = array_intersect_key($toBeSorted, array_flip($sortByThis));
// Sort the remaining portion
$remain = array_diff_key($toBeSorted, $sorted);
ksort($remain);
$toBeSorted = array_merge($sorted, $remain);
You could use uksort to put together.你可以使用uksort来组合。
uksort($toBeSorted, function($a, $b) use ($sortByThis) {
$key_a = array_search($a, $sortByThis);
$key_b = array_search($b, $sortByThis);
if ($key_a === false && $key_b === false) {
return strcmp($a, $b);
} else if ($key_a === false) {
return 1;
} else if ($key_b === false) {
return -1;
} else {
return $key_a - $key_b;
}
});
have a look on array_multisort() function.看看 array_multisort() 函数。 http://php.net/manual/en/function.array-multisort.php
http://php.net/manual/en/function.array-multisort.php
You can achieve this by doing something like this.你可以通过做这样的事情来实现这一点。
$sorted_arr= array_multisort($toBeSorted, array('username'=>SORT_ASC, 'id'=>SORT_ASC));
If this not help you there are other functions submitted by users.如果这对您没有帮助,还有用户提交的其他功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.