简体   繁体   English

遍历foreach中的第一个项目两次

[英]Loop through first item in foreach twice

I'm trying to figure out the cleanest way to loop through the first item in an array twice. 我试图找出最干净的方法两次遍历数组中的第一项。 My foreach looks like this: 我的foreach看起来像这样:

foreach ($array as $arr) {
    $arr['item'];
}

The reason I'm asking is because I'm looping through and running a curl script that requires setting a cookie. 我问的原因是因为我正在循环并运行需要设置cookie的curl脚本。 On the first loop, it's not setting properly but it is on all others. 在第一个循环中,它的设置不正确,但在所有其他循环中都设置得正确。 Ideally I'd like to just hit that first twice, and overwrite the value I'm pulling. 理想情况下,我想先打两次,然后覆盖我要提取的值。

If you need to make something twice with 1st element, you can make it this way 如果您需要用1st元素制作两次,可以这样

$firstItem = true;
foreach ($array as $arr) {
    if ($firstItem) {
       $arr['item'];
       $arr['item'];
       $firstItem = false;
    } else {
       $arr['item'];
    }
}

But instead of making it twice, maybe you should find out why it doesn't work first time? 但是,也许您不应该两次制作它,而是应该找出为什么它第一次不起作用? +1 to previous comment that you should fix a problem, but not workaround it. +1对先前的评论,您应该解决问题,但不能解决。

If order is not important: 如果顺序不重要:

  array_push($array, reset($array));
  foreach ($array as $arr) {
      ...
  }

If it is, better use Elena's suggestion. 如果是这样,最好使用Elena的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM