合并PHP数组中的重叠范围? [英] Merging overlapping ranges in PHP arrays?

查看:34
本文介绍了合并PHP数组中的重叠范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个格式如下的数组:

I have an array in the following format:

array(
  0 => array(1, 5),
  1 => array(4, 8),
  2 => array(19, 24),
  3 => array(6, 9),
  4 => array(11, 17),
);

其中每个项目都是 X 到 Y 的范围.我想合并数组中的重叠范围,以获得更像这样的东西:

Where each item is a X-to-Y range. What I would like to merge the overlapping ranges in the array, to get something more like this:

array(
  0 => array(1, 9), // 1-5, 4-8 and 6-9 are overlapping, so they are merged
  1 => array(11, 17),
  2 => array(19, 24),
);

最好的方法是什么?

推荐答案

未测试,但这里的想法是先按第一个元素对数据进行排序,然后尽可能将后面的元素与前一个元素合并.

Untested, but the idea here is to sort the data first by the first element, then merge subsequent elements with the previous one as long as possible.

usort($data, function($a, $b)
{
        return $a[0] - $b[0];
});

$n = 0; $len = count($data);
for ($i = 1; $i < $len; ++$i)
{
        if ($data[$i][0] > $data[$n][1] + 1)
                $n = $i;
        else
        {
                if ($data[$n][1] < $data[$i][1])
                        $data[$n][1] = $data[$i][1];
                unset($data[$i]);
        }
}

$data = array_values($data);

这篇关于合并PHP数组中的重叠范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆