【问题标题】:Insert array in collection after specific index in laravel在laravel中的特定索引之后将数组插入集合中
【发布时间】:2017-11-20 13:24:40
【问题描述】:

我想在 laravel 集合中的特定索引之后插入项目(数组)。我正在使用此代码:

 foreach ($posts as $key => $post) {
      foreach ($friendsArray as $date => $friend) {
        if ($post->updated_at->format('Y-m-d') == $date) {
            $posts->push($friend);
            $friendsArray->forget($date);
        }
      }
   }

   dd($posts);

结果如下:

#items: array:9 [▼
      0 => Post {#862 ▶}
      1 => Post {#863 ▶}
      2 => Post {#864 ▶}
      3 => Post {#865 ▶}
      4 => Post {#866 ▶}
      5 => Post {#867 ▶}
      6 => Post {#868 ▶}
      7 => Post {#869 ▶}
      8 => Collection {#956 ▶}
    ]

问题是集合帮助 Push 在最后插入值但我想在特定索引之后插入。例如,我想在第二个数组之后插入它。

提前致谢

【问题讨论】:

  • 如果你想插入任何条件检查简单检查条件并将其放入另一个数组,然后插入整个数组。

标签: laravel collections


【解决方案1】:

您可以使用splice(int $offset, int|null $length = null, mixed $replacement = []) 方法。

例子:

// $offset as the postition
// 0 because you don't want to remove any items
// $friend as replacement
$posts->splice($offset, 0, $friend);

documentation

【讨论】:

  • 我很乐意提供帮助。您能否将此标记为答案,以便其他人可以看到?
【解决方案2】:

试试这个:

foreach ($posts as $key => $post) {
      foreach ($friendsArray as $date => $friend) {
        if ($post->updated_at->format('Y-m-d') == $date) {
            $post->friend = $friend;
        }
      }
   }

   dd($posts);

【讨论】:

  • 首先删除第二个foreach,然后通过将数组传递给朋友进行测试...
  • 先删除第二个foreach,然后测试。
  • 请提供一个可行的解决方案。答案不应该包括猜测
  • 欢迎来到 Stack Overflow!感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。一个正确的解释would greatly improve 其长期价值,通过展示为什么这是解决问题的好方法,并将使其对未来有其他类似问题的读者更有用。请edit您的回答添加一些解释,包括您所做的假设。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-11
  • 1970-01-01
  • 2019-11-20
  • 1970-01-01
  • 2016-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多