Initially i have an array list like this:
[
[
"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"
]
]
I want to add 'custom' at position 1 in each array - something like this:
[
[
"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"
]
]
What is the appropriate way to push this 'custom' in php, without iterating over the arrays?
CodePudding user response:
You can do like this :
foreach ($data as $key => $value) {
array_splice($data[$key], 1, 0, "custom");
}
CodePudding user response:
You can use the array_map function for that:
$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
Or just a simple foreach:
foreach($array as $index => $el) {
array_splice($array[$index], 1, 0, "custom");
}