0

我想知道是否有更好的解决方案可以从中间到结束然后从开始到中间循环遍历数组。特别是对于关联数组。

例如,如果有一个带有键的关联数组

$dow = array(Mon => etc, Tue => etc, Wed  => etc, Thr  => etc .. to .. Sun  => etc). 

我会从星期四开始搜索数组以查找第二天的特定内容,可能是任何一天但恰好在星期二,我通常从星期四(按索引)迭代到星期日,然后重置并从星期一到星期三重新开始并找到到达星期二时的目标。

我通过 id 计算索引,当它达到 6 时将 id 重置为 0

 $id = 3 // Found day is Thursday id

//Loop function starts here   
$id++; // start search from one day above found day
 if ($id >= 6){ //when reaching Sunday
    $id = 0 // start search from monday
  }  
// check array here for that specific thing

所以问题是问是否有比这更简单的解决方案,即从周四到周日的索引拆分数组并将其添加到数组的开头,然后执行循环而无需计算索引或是否有任何其他不使用计数索引的解决方案。

4

4 回答 4

0

您可以尝试使用array_splice

$array = array(1,2,3,4,5,6,7);

$lastDays = array_splice($array, 3);
$firstDays = $array;

print_r(array('first days' => $firstDays, 'last days' => $lastDays));

如果日期不在$lastDays(使用布尔值$matchFound),那么您将在$firstDays.

或者只是与array_merge一起使用:

$array = array(1,2,3,4,5,6,7);

$array = array_merge(array_splice($array, 3), $array);
print_r($array);

其中输出是:

Array
(
    [0] => 4
    [1] => 5
    [2] => 6
    [3] => 7
    [4] => 1
    [5] => 2
    [6] => 3
)

然后您可以使用foreach.

于 2013-05-28T07:15:49.620 回答
0

也许 foreach 会更有效。希望这可以帮助。

$id = 3 // Found day is Thursday id
$i =0;
//Loop function starts here   
foreach($dow as $idx)
   if($id == $i):

   else if($i > $id):


   endif;

   if($i == count($dow)){$i=0;}else{$i++;}
endforeach;
于 2013-05-28T07:17:53.313 回答
0
<?php

    $dow = array("mon","tue","wed","thu","fri","sat","sun");

    $pick_a_day = 2; // user input; NON zero based. monday = 1
    $pick_a_day--; // make it zero based to use in code

    foreach($dow as $inc => $an_element )
    {
        echo $dow[($pick_a_day+(count($dow))) % (count($dow))]." - loop number:".($inc+1)."\n";
        $pick_a_day++;
    }

?>

输出

tue - loop number:1
wed - loop number:2
thu - loop number:3
fri - loop number:4
sat - loop number:5
sun - loop number:6
mon - loop number:7
于 2013-05-28T07:20:24.607 回答
0

也许不是最好的解决方案,而是一个解决方案:

function half($array) {
    $h = sizeof($array) / 2;
    $a1 = array_splice($array, $h);
    $a2 = array_splice($array, 0);
    $res = array_merge($a1, $a2);
    return $res;
}

$dow = array('Mon' => 'etc1', 'Tue' => 'etc2', 'Wed'  => 'etc3', 'Thr'  => 'etc4', 'Fri' => 'etc5', 'Sat' => 'etc6', 'Sun' => 'etc7');

$b = half($dow);

现在你可以通过一个 foreach 或者你想要的方式。$b 的结果:

Array
(
    [Thr] => etc4
    [Fri] => etc5
    [Sat] => etc6
    [Sun] => etc7
    [Mon] => etc1
    [Tue] => etc2
    [Wed] => etc3
)
于 2013-05-28T07:27:57.293 回答