如何添加一个项目在位置1,为多个数组在同一时间



最初我有一个像这样的数组列表:

[
[
"hi",
"hi",
"hi",
"",
"hi",
"2021-11-29 00:00:00",
"4"
],
[
"custom title",
"new custom",
"customurl.com",
"https://wpsn.test/wp-content/uploads/2021/09/vnech-tee-blue-1.jpg",
"Custom Description",
"2022-01-12 00:00:00",
"4"
],
[
"new title",
"suvro",
"www.suvro.com",
"",
"new description",
"2022-01-26 00:00:00",
"4"
]
]

我想在每个数组的位置1添加'custom' -像这样:

[
[
"hi",
"custom",
"hi",
"hi",
"",
"hi",
"2021-11-29 00:00:00",
"4"
],
[
"custom title",
"custom",
"new custom",
"customurl.com",
"https://wpsn.test/wp-content/uploads/2021/09/vnech-tee-blue-1.jpg",
"Custom Description",
"2022-01-12 00:00:00",
"4"
],
[
"new title",
"custom",
"suvro",
"www.suvro.com",
"",
"new description",
"2022-01-26 00:00:00",
"4"
]
]

在php中推送这个"自定义"而不迭代数组的合适方法是什么?

你可以这样做:

foreach ($data as $key => $value) {
array_splice($data[$key], 1, 0, "custom");
}

可以使用array_map函数:

$newArray = array_map(function($el) {
array_splice($el, 1, 0, "custom"); // Insert "custom" at position 1
return $el;
}, $array); // $array is the array you want to modify

或者只是一个简单的foreach:

foreach($array as $index => $el) {
array_splice($array[$index], 1, 0, "custom");
}

最新更新