array_splice()
是 PHP 中用于添加、刪除或替換數組元素的函數
foreach
遍歷多維數組:$multiArray = [
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']
];
foreach ($multiArray as $key => $subArray) {
array_splice($multiArray[$key], 1, 0, 'x'); // 在每個子數組的第二個位置插入 'x'
}
print_r($multiArray);
輸出結果:
Array
(
[0] => Array
(
[0] => a
[1] => x
[2] => b
[3] => c
)
[1] => Array
(
[0] => d
[1] => x
[2] => e
[3] => f
)
[2] => Array
(
[0] => g
[1] => x
[2] => h
[3] => i
)
)
array_map()
處理多維數組:$multiArray = [
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']
];
$result = array_map(function ($subArray) {
array_splice($subArray, 1, 0, 'x'); // 在每個子數組的第二個位置插入 'x'
return $subArray;
}, $multiArray);
print_r($result);
輸出結果:
Array
(
[0] => Array
(
[0] => a
[1] => x
[2] => b
[3] => c
)
[1] => Array
(
[0] => d
[1] => x
[2] => e
[3] => f
)
[2] => Array
(
[0] => g
[1] => x
[2] => h
[3] => i
)
)
這些方法可以幫助你在多維數組中使用 array_splice()
函數。根據需要,你可以調整這些示例以滿足特定的操作需求。