我有一个数组:
$pics = array("0"=>"pic-1", "1"=>"pic-2", "2"=>"pic-3", "3"=>"pic-4", "4"=>"pic-5");
我希望将它从低到高排序,但是从定义的非0起点开始,然后在结尾添加剩余的值,也从低到高。
所以例如以键2为起点我想以
结尾$pics = array("2"=>"pic-3", "3"=>"pic-4", "4"=>"pic-5", "0"=>"pic-1", "1"=>"pic-2");
有人可以向我解释如何做到这一点吗?
答案 0 :(得分:0)
我解决了这个问题,请检查一下:
<?php
//
// $start: starting position to sort in [0, count($xarr) - 1].
//
function sortArrayFromPosition($xarr, $start)
{
//
if($start < 0)
{
return $xarr;
}
elseif($start >= count($xarr))
{
return $xarr;
}
//
// sort the ending elements:
//
$ends = array_slice($xarr, $start, null, true);
asort($ends);
//
// append beginning elements:
//
$i = 0;
foreach($xarr as $key => $value)
{
if($i > $start)
{
$break;
}
$ends[$key] = $value;
$i++;
}
return $ends;
}
//
// main tests:
//
//$pics = array("0"=>"pic-1", "1"=>"pic-2", "2"=>"pic-3", "3"=>"pic-4", "4"=>"pic-5");
$pics0 = array("0"=>"pic-1", "1"=>"pic-5", "2"=>"pic-3", "3"=>"pic-2", "4"=>"pic-4");
//
$start = 2;
$pics = sortArrayFromPosition($pics0, $start);
//
echo "<pre>";
print_r($pics);
echo "</pre>";
//
$start = 4;
$pics = sortArrayFromPosition($pics0, $start);
//
echo "<pre>";
print_r($pics);
echo "</pre>";
?>