封装获取连续数字的拼接

    /*
     * 获取连续数字拼接
     * $arr = array(
            'dev' => array(1, 2, 3, 4, 10, 20, 21, 22),
            'dev2' => array(1, 2, 3, 50),
            'dev3' => array(1)
        );
    *结果:    
        [dev] => devs1-2
        [dev2] => dev2s1
    */
    public function getContinuouStr($arr){
        $ret = array();
        foreach ($arr as $agent => $server_arr) {
            $count = count($server_arr);    //个数
            $start = $server_arr[0];    //连续段的起始值
            $pre = $start;  //上一个数
            $_ret = array();
            $_ret = array($start => 0);
            for($i = 1; $i < $count; $i ++) {
                $cur = $server_arr[$i];
                if($cur - $pre == 1) {  //是连续
                    $_ret[$start] = $cur;
                } else {    //不连续
                    $start = $cur;
                    $_ret[$start] = 0;
                }
                $pre = $cur;
            }
            $ret[$agent] = $_ret;
        } 

        $ret2 = array();
        foreach ($ret as $agent => $server_arr) {
            $str = '';
            foreach ($server_arr as $k => $val) {
                if($val > 0) {
                    $str .= $agent . 's' . $k . '-' . $val . '&';
                } else {
                    $str .= $agent . 's' . $k . '&';
                }
            }
            $str = rtrim($str, '&');
            $ret2[$agent] = $str;
        } 
        return $ret2;
    }

 

posted @ 2018-01-17 19:42  lonmy  阅读(243)  评论(0编辑  收藏  举报