【发布时间】:2015-12-02 14:07:58
【问题描述】:
我正在尝试根据key=>value 对数组进行排序,但我无法完成此操作。这是我正在编写的代码:
$arr = [
'183034' => 9,
'183033' => 6,
'183032' => 3,
'183002' => null,
'182973' => null,
'182971' => null,
'182969' => null,
'182999' => null,
'182997' => null,
'182995' => null,
'182962' => null,
'182948' => null
];
$arrTemp = [];
foreach($arr as $key => $value) {
$arrTemp[$key] = $value;
}
array_multisort($arrTemp, SORT_NUMERIC, $arr);
var_export($arrTemp);
输出是:
#php test.php
array (
0 => NULL,
1 => NULL,
2 => NULL,
3 => NULL,
4 => NULL,
5 => NULL,
6 => NULL,
7 => NULL,
8 => NULL,
9 => 3,
10 => 6,
11 => 9,
)
但我希望是这样的:
array (
'183002' => null,
'182973' => null,
'182971' => null,
'183032' => 3,
'182969' => null,
'182999' => null,
'183033' => 6,
'182997' => null,
'182995' => null,
'183034' => 9,
'182962' => null,
'182948' => null
);
where value 定义了项目应该移动的位置。换句话说,让我们举个例子:'183032' => 3 这个项目在结果数组上保持位置 3,所以我应该做的是保持相同的数组顺序,但将该项目移动到位置 3,正如您在输出数组上可能注意到的那样。 '183033' => 6 也是如此,其中这个持有位置 6,所以我重新排列整个数组以将其移动到位置 6,依此类推。有谁能帮帮我吗?
更新
如果我把原来的$arr改成这样:
$arr = [
'183034' => ['sort_position' => 9],
'183033' => ['sort_position' => 5],
'183032' => ['sort_position' => 3],
'183002' => [],
'182973' => [],
'182971' => [],
'182969' => [],
'182999' => [],
'182997' => [],
'182995' => [],
'182962' => [],
'182948' => []
];
几乎相同,但这就是数组的外观(只是一个示例),带有[] 的数组内部应该有其他键我只是不在这里写它们,因为相关的是sort_position。
【问题讨论】:
-
试试php.net,非常棒:)
-
也许
SORT_DESC | SORT_NUMERIC?? -
你能解释一下输出吗,你想要。
-
@DamienPirsy 所需的输出键不是
ASC的顺序 -
你试过简单的
krsort()
标签: php arrays algorithm sorting