我正在尝试根据排序数组,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
);
其中,值定义了应继续移动项目的位置。换句话说,让我们用一个例子来举例说明:'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
。
$arr = [
'183034' => ['sort_position' => 9],
'183033' => ['sort_position' => 5],
'183032' => ['sort_position' => 3],
'183002' => [],
'182973' => [],
'182971' => [],
'182969' => [],
'182999' => [],
'182997' => [],
'182995' => [],
'182962' => [],
'182948' => []
];
$count = count($arr);
$tmp=[];
//sort by key descending
krsort($arr);
foreach($arr as $key=>$val){
//if element has a sort position
if(isset($val['sort_position'])){
//save it in tmp, indexed by sort position
$tmp[$val['sort_position']]=$val;
//and remove it from original array
unset($arr[$key]);
}
}
//Note $arr now only contains elements without sort position
$out=[];
//build new array of same length as original
for($i=0; $i < $count; $i++){
//if there is an element in temp with this sort position, use it
//else grab the next one from the non sort position elements
$out[] = isset($tmp[$i])? $tmp[$i] : array_shift($arr);
}
var_dump($out);
编辑只是意识到我错过了数组键的重要性。也许您实际上根本不需要密钥,但是为了完整起见,这里有一个修改后的解决方案,它也保留了密钥:
$count = count($arr);
$has_sortorder=[];
$no_sortorder=[];
krsort($arr);
foreach($arr as $key=>$val){
if(isset($val['sort_position'])){
$has_sortorder[$val['sort_position']]=[$key, $val];
}else{
$no_sortorder[]=[$key, $val];
}
}
$out=[];
for($i=0; $i < $count; $i++){
if(isset($has_sortorder[$i])){
$out[$has_sortorder[$i][0]] = $has_sortorder[$i][1];
}else{
$element = array_shift($no_sortorder);
$out[$element[0]] = $element[1];
}
}
var_dump($out);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句