>  기사  >  백엔드 개발  >  完善以下PHP代码中的insertAt函数,实现在数组$items的任意位置插入数据

完善以下PHP代码中的insertAt函数,实现在数组$items的任意位置插入数据

WBOY
WBOY원래의
2016-06-06 20:37:311066검색

$items= ['苹果','橘子','梨','菠萝','香蕉','火龙果'] ;

/*
$items 传入的数组
$index 要插入的位置
$value 要插入的数据
*/
function insertAt($items, $index, $value) {

<code>return $items;
</code>

}

$items=insertAt($items, 2 , '橙子'); //执行完成后,得到的结果如下
['苹果','橘子','橙子','梨','菠萝','香蕉','火龙果'] ;

回复内容:

$items= ['苹果','橘子','梨','菠萝','香蕉','火龙果'] ;

/*
$items 传入的数组
$index 要插入的位置
$value 要插入的数据
*/
function insertAt($items, $index, $value) {

<code>return $items;
</code>

}

$items=insertAt($items, 2 , '橙子'); //执行完成后,得到的结果如下
['苹果','橘子','橙子','梨','菠萝','香蕉','火龙果'] ;

<code>php</code><code><?php $items= ['苹果','橘子','梨','菠萝','香蕉','火龙果'] ;

/*
$items 传入的数组
$index 要插入的位置
$value 要插入的数据
*/
function insertAt($items, $index, $value) {
    array_splice ( $items , $index ,  0 , $value);

    return $items;
}


$out = insertAt($items,2,'橙子');

var_dump($out);

/* return 
array (size=7)
  0 => string '苹果' (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)
 */
</code>

@宋小北 提到的array_splice是php原生实现。我们千万不要重复造轮子。

这里造一个,仅为了好玩。

<code>function insertAt($items, $value, $index=0) {
    is_numeric($index) and
    $items[($index-'0.1').'x'] = $value and
    ksort($items);
    return array_values($items);
}
</code>
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.