【问题标题】:Normalize array values in natural order PHP以自然顺序 PHP 规范化数组值
【发布时间】: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


    【解决方案1】:

    如果您需要使用自定义排序算法,请使用usort 执行此操作。来自 PhP 的文档:

    如果认为第一个参数分别小于、等于或大于第二个参数,则比较函数必须返回一个小于、等于或大于零的整数。

    因此,如果您需要提供这些整数,以防某个项目“更大”或“更低”,usort 会为您完成这项工作。

    在你的情况下,它可能会导致这个功能:

    <?php
        function sort_items_map($a, $b)
        {
            $value = 0;
    
            if( $a < $b )
            {
                $value = -1;
            }
            else if( $a > $b )
            {
                $value = 1;
            }
            else if( $a == $b )
            {
                $value = 0;
            }
    
            return $value;
        }
    
        $items_map = [1, 3, 1, 7]; // or fill it with your own values
    
        usort($items_map, "sort_items_map");
    ?>
    

    【讨论】:

    • 感谢您的回答,但您的代码只排序,我需要项目按自然顺序排列,请参阅我的编辑。
    猜你喜欢
    • 2021-06-18
    • 2020-06-13
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    • 2021-03-02
    相关资源
    最近更新 更多