我想在提供所需索引顺序的基础上重组数组(而不是传统排序(,例如[1,7,4]。下面只是根据值升序排序。
想要的结果:
Array
(
[1] => c
[4] => b
[7] => a
)
我的代码:
$array = [];
$array[4] = "b";
$array[1] = "c";
$array[7] = "a";
print_r($array);
echo "nn" . "Sort ascending..." . "nn";
asort($array);
print_r($array);
结果:
Array
(
[4] => b
[1] => c
[7] => a
)
Sort ascending...
Array
(
[7] => a
[4] => b
[1] => c
)
请使用rsort 进行测试
$array = [];
$array[4] = "b";
$array[1] = "c";
$array[7] = "a";
print_r($array);
echo "nn" . "Sort ascending..." . "nn";
rsort($array); //sort descending
print_r($array);
因此,您需要构建一个自定义函数,以便为自定义排序传递排序键。这将获取您的密钥,然后从数组中提取每个密钥,并根据需要以正确的顺序构建一个新数组。
$array = [];
$array[4] = "b";
$array[1] = "c";
$array[7] = "a";
function sortByKeyOrder(array $sortOrderKeys, array $arrayToSort){
$output = [];
foreach($sortOrderKeys as $index){
if(isset($arrayToSort[$index])){
$output[$index] = $arrayToSort[$index];
}
}
return $output;
}
//usage
sortByKeyOrder([1, 4, 7], $array);
ksort
正在按key
对数组中的项目进行排序
ksort($array);
Array
(
[1] => c
[4] => b
[7] => a
)
这是你所期望的吗?
//-- your array
$array = [];
$array[4] = "b";
$array[1] = "c";
$array[7] = "a";
print_r( $array );
//-- the order you want to sort
$input_index = [1,4,7];
//-- new array
$new_array = [];
foreach( $input_index as $i )
{
$new_array[ $i ] = $array[ $i ];
}
print_r( $new_array );
输出:
Array (
[4] => b
[1] => c
[7] => a
)
Array (
[1] => c
[4] => b
[7] => a
)