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()
函数。根据需要,你可以调整这些示例以满足特定的操作需求。