【发布时间】:2017-01-02 14:59:25
【问题描述】:
我遇到了这个问题,我需要在删除某些项目后对数组中的自然顺序值进行规范化/排序。
考虑以下示例。初始数组
{ [313]=> int(2) [303]=> int(1) [295]=> int(3) [290]=> int(4) }
排序数组
{ [303]=> int(1) [313]=> int(2) [295]=> int(3) [290]=> int(4) }
考虑当我们删除第一个项目时,数组现在应该是这样的
{ [313]=> int(1) [295]=> int(2) [290]=> int(3) }
如果项目在数组范围内,例如295 (3),它应该是
{ [303]=> int(1) [313]=> int(2) [290]=> int(3) }
我希望你有一个想法。 但是我的功能不能正确地做到这一点。 我已经实现了这种排序的一部分,这里是代码,但也许还有其他方法可以更容易地做到这一点?
const MIN_VALUE = 1;
public function sort_items(&$items_map)
{
if (!empty($items_map)) {
asort($items_map);
var_dump($items_map);
$first_item = reset($items_map);
if ($first_item > self::MIN_VALUE) {
$normalize_delta = $first_item - self::MIN_VALUE;
$prev_item_id = null;
foreach ($items_map as $id => $part) {
$items_map[$id] = $part - $normalize_delta;
if (!empty($prev_item_id)) {
$difference = $items_map[$id] - $items_map[$prev_item_id];
if ($difference > 1) {
$items_map[$id] = $items_map[$id] - ($difference - 1);
}
}
$prev_item_id = $id;
}
}
}
return $items_map;
}
如果有任何帮助,我将不胜感激。
谢谢
更新
澄清一下。
我希望项目不只是按正确的顺序排序,而是按自然顺序排列,例如
序列1,3,5,6,7,9 应转换为1,2,3,4,5,6,但保持keys 相同。
2,3,7,9 => 1,2,3,4
请看我上面的例子,用真实的单词大小写。
【问题讨论】:
标签: php arrays algorithm sorting dictionary