$items= ['苹果','橘子','梨','菠萝','香蕉','火龙果'] ;
/*
$items 传入的数组
$index 要插入的位置
$value 要插入的数据
*/
function insertAt($items, $index, $value) {
return $items;
}
$items=insertAt($items, 2 , '橙子'); //执行完成后,得到的结果如下
['苹果','橘子','橙子','梨','菠萝','香蕉','火龙果'] ;
回复内容:
$items= ['苹果','橘子','梨','菠萝','香蕉','火龙果'] ;
/*
$items 传入的数组
$index 要插入的位置
$value 要插入的数据
*/
function insertAt($items, $index, $value) {
return $items;
}
$items=insertAt($items, 2 , '橙子'); //执行完成后,得到的结果如下
['苹果','橘子','橙子','梨','菠萝','香蕉','火龙果'] ;
phpstring '苹果' (length=6)
1 => string '橘子' (length=6)
2 => string '橙子' (length=6)
3 => string '梨' (length=3)
4 => string '菠萝' (length=6)
5 => string '香蕉' (length=6)
6 => string '火龙果' (length=9)
*/
@宋小北 提到的array_splice是php原生实现。我们千万不要重复造轮子。
这里造一个,仅为了好玩。
function insertAt($items, $value, $index=0) {
is_numeric($index) and
$items[($index-'0.1').'x'] = $value and
ksort($items);
return array_values($items);
}
相关标签:php 数组
本文原创发布php中文网,转载请注明出处,感谢您的尊重!