我在php中有一个问题,我想根据它们的键重新索引数组的值,以便使每个数组具有相同的顺序,以便能够轻松地比较它们(删除重复项),它应该适用于任何长度的数组删除重复项。
例如A,C,B,D / D,B,C,A / C,A,B,D应该被重新排序以具有值A,B,C,D,因为给定的字符列表其指数为0-> A,1-> B,2-> C,3-> D
例如,假设我们有这个数组Array(
[0] => Array (
[0] => S,
[1] => E,
[2] => Q,
[3] => A
)
)
我们有一个带索引的字符列表(带有索引的字符):
// index --> character ( array with real indexes)
$array_real_index = Array(
[0] => A,
[1] => C,
[2] => D,
[3] => B,
[4] => E,
[5] => Q,
[6] => R,
[7] => S
)
如果找到字符索引应该用正确的索引替换(如果不是正确的索引)。
所以结果应该是:
Array (
[0] => A,
[1] => E,
[2] => Q,
[3] => S
)
感谢您将来的帮助。
答案 0 :(得分:0)
试试这个:
<?
$sorted_array = array_intersect($sort_array, $array_real_index);
sort($sorted_array);
print_r($sorted_array);
?>
答案 1 :(得分:0)
$original_array = Array(
0 => 'S',
1 => 'E',
2 => 'Q',
3 => 'A'
);
$array_real_index = Array(
0 => 'A',
1 => 'C',
2 => 'D',
3 => 'B',
4 => 'E',
5 => 'Q',
6 => 'R',
7 => 'S'
);
// Custom sorting function passed to usort. $a & $b are two values
// being compared in terms of how they should be sorted. Results:
// 1: $a > $b (move $b down one and $a up one)
// -1: $b > $a (move $a down one and $b up one)
// 0: $a == $b (no change)
function sort_using_real_index($a,$b){
// allow access to $array_real_index from within this function
global $array_real_index;
// retrieve the key indexes of the values. E.g. $a might contain
// 'R', array_search would return 6.
$aI = array_search($a, $array_real_index);
$bI = array_search($b, $array_real_index);
// Both the found keys are then compared and returned
// (1, -1 and 0 results reflect how $a and $b relate in terms
// of sort order within the sorted result)
return $aI == $bI
? 0
: ($aI > $bI ? 1 : -1);
}
// dump out the original array (benchmark)
var_dump($original_array);
// sort the original array using the custom function
usort($original_array, 'sort_using_real_index');
// output the sorted result
var_dump($original_array);
正如其他人所说,您可以使用usort
并传递一个自定义函数,该函数使用一个数组中的键作为sort函数中的比较器。
想要使用usort
演示如何使用您认为最有用的指标对数组进行排序。
答案 2 :(得分:0)
usort()
系列函数之一。array_filter()
。代码:
$master = array('A', 'C', 'D', 'B', 'E', 'Q', 'R', 'S');
function myCompare($a, $b) {
global $master;
$index_a = array_search($a, $master, TRUE);
$index_b = array_search($b, $master, TRUE);
if( $index_a === false && $index_b === false ) {
// if neither are in the array, then sort by their normal value
return ($a === $b) ? 0 : ($a < $b) ? -1 : 1;
} else if( $index_a === false ) {
// if only one is in the array, then it is "greater" than the other
return 1;
} else if( $index_b === false ) {
return -1;
} else {
// otherwise the item with the lowest index is the "greater" of the two
return ($index_a === $index_b) ? 0 : ($index_a < $index_b) ? -1 : 1;
}
}
function myFilter($var) {
global $master;
return in_array($var, $master);
}
$input = array('A','B','C','D','E','F','G','H');
$input = array_filter($input, 'myFilter');
usort($input, 'myCompare');
print_r($input);
/* Output:
Array
(
[0] => A
[1] => C
[2] => D
[3] => B
[4] => E
) */