2012-08-10 88 views
1

我遇到了PHP排序整数从1开始到一些值,其中排序基于一个选定的整数,其值在1和某个值之间。基于选定整数的PHP排序整数

下面是我想要的功能看:

function sort_integers($count, $selected_value){ 
    ....sort()...? 
} 

所以,如果$count=7,你$selected_value=3,那么sort_integers()函数将返回此:

3,4,5,6,7,1,2 

而且如果$count=4和你$selected_value=2,那么sort_integers()函数会返回这个:

2, 3, 4, 1 

我想我需要一个增量的第三个变量,这样我可以做一个比较,但是我的脑袋正在开始考虑如何去做这件事。思考?

+0

解决方法:像往常一样对数组进行排序,然后执行一些拼接操作,将第一部分移动到数组的末尾,在您想要对整数进行排序的$ selected_value – 2012-08-10 15:09:32

+1

处进行拆分,或者将所有整数从$ selected_value以升序显示到$ count其次是1到$ count-1的升序? – 2012-08-10 15:09:37

+0

@MarcB你能分享一些代码来解释你的解决方法吗? – 2012-08-10 15:11:38

回答

5

如果我给你的权利,我这样做:

function sort_integers($count, $selected_value){ 
    $res = array(); 
    for($i = $selected_value; $i <= $count; ++$i) 
     $res[] = $i; 
    for($i = 1; $i < $selected_value; ++$i) 
     $res[] = $i; 
    return $res; 
} 

,或者使用内置函数:

function sort_integers($count, $selected_value){ 
    return array_merge(range($selected_value, $count), 
         range(1, $selected_value - 1)); 
} 

这是假设你只是要对齐的值就像在你的例子,有没有给定的数组,你想排序(因为你没有通过一个,并没有提到一个)。

2

范围已经排序,你只把它分解和扭转部分:

$count = 7; 
$selected = 3; 

$range = range(1, $count); 

if (--$selected) 
{ 
    $sort = array_splice($range, 0, $selected); 
    $sort = array_merge($range, $sort); 
} else { 
    $sort = $range; 
} 

或者更直截了当:

function sort_integers($count = 7, $selected = 3) { 
    if (! $count = max(0, $count)) return array(); 
    if (--$selected && $selected < $count) { 
     return array_merge(range($selected+1,$count), range(1, $selected)); 
    } 
    return range(1, $count); 
} 
1

不阵列,这应该工作..

function sort_integers($count, $selected_value) 
{ 
    for($x = $selected_value; $x<=$count;$x++) 
    { 
     echo $x.","; 
    } 

    for($x=1; $x < $selected_value;$x++) 
    { 
     echo $x.","; 
    } 
} 

哦,它可能会留下额外的逗号..