我想在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 ▶}
]
问题是集合帮助推送插入最后一个值,但我想在特定索引后插入。例如,我想在第二个数组之后使用它。
提前致谢
答案 0 :(得分:0)
试试这个:
foreach ($posts as $key => $post) {
foreach ($friendsArray as $date => $friend) {
if ($post->updated_at->format('Y-m-d') == $date) {
$post->friend = $friend;
}
}
}
dd($posts);
答案 1 :(得分:0)
您可以使用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。