2

我有一个变量长度数组,包含按 startdate 排序的事件,如下所示:

Array
(
[0] => stdClass Object
    (
        [id] => 1978
        [date] => 2012-09-29
    )

[1] => stdClass Object
    (
        [id] => 1979
        [date] => 2012-10-14
    )

...etc....

我需要创建一个函数来获取其中一个事件,并将其放在一个长度正好为 7 的新数组的中间,并将事件的邻居放在每一侧。

因此,如果事件 5 传递给函数,则输出应为:

[2][3][4][5][6][7][8]

如果第一个事件被传递给函数,并且事件的原始数量是 12,那么输出应该是:

[10][11][12][1][2][3][4]

如果事件的原始数量为 6,并且通过了第五个事件,则输出应为:

[2][3][4][5][6][1][]

所以事件列表应该总是在新数组中“环绕”并尽可能多地填充它。

我已经破解了一个解决方案,其中涉及相当多的步骤。我真的不喜欢它,这让我想知道:

这将如何以最有效和最优雅的方式完成?

4

1 回答 1

1
You need to change the values in this codes
  define('TO_SHOW',7); // number of items to show in your case it is 7
  $selected      = 1; //// which one you need need at center.

和你的阵列;

执行此操作并尝试:

<?php 

define('TO_SHOW',7); // number of items to show in your case it is 7

function change_order($arry, $sel){
   $arr_cnt      = count($arry);   
   $shift_count  = $arr_cnt - (ceil(TO_SHOW/2)-$sel);
   for($i=0; $i<$shift_count; $i++){
      array_push($arry, array_shift($arry));
   }
   return array_slice($arry, 0, TO_SHOW);
} 

$arr            = array(array(
                    "id" => 1,
                    "date" => 2012-09-29
                    ),
                    array(
                    "id" => 2,
                    "date" => 2012-09-29
                    ),
                    array(
                    "id" => 3,
                    "date" => 2012-09-29
                    ),
                    array(
                    "id" => 4,
                    "date" => 2012-09-29
                    ),
                    array(
                    "id" => 5,
                    "date" => 2012-09-29
                    ),
                    array(
                    "id" => 6,
                    "date" => 2012-09-29
                    ),
                    array(
                    "id" => 7,
                    "date" => 2012-09-29
                    ),
                    array(
                    "id" => 8,
                    "date" => 2012-09-29
                    ),
                    array(
                    "id" => 9,
                    "date" => 2012-09-29
                    ),
                    array(
                    "id" => 10,
                    "date" => 2012-09-29
                    ),
                    array(
                    "id" => 11,
                    "date" => 2012-09-29
                    ),
                    array(
                    "id" => 12,
                    "date" => 2012-09-29
                    ),
                    array(
                    "id" => 13,
                    "date" => 2012-09-29
                    ),
                    array(
                    "id" => 14,
                    "date" => 2012-09-29
                    )
                );

$selected      = 1; //// centre one             
$test   = change_order($arr, $selected);

echo "<pre>";
print_r($test);
?>
于 2013-01-25T10:57:24.507 回答