向数组中任意位置添加元素实现

array_slice(array,start,length,preserve) 函数在数组中根据条件取出一段值,并返回。

 public static function rand_array_push($array, $data = [], $key=false){
        //找到需要在哪个位置添加的索引号
        $offset  = ($key == false) ? false: (array_search($key, array_keys($array))+1);
        if($offset){
            return array_merge(
                array_slice($array, 0, $offset),
                $data,
                array_slice($array, $offset)
            );
        }else{
            // 没指定 $key 或者找不到,就直接加到末尾
            return array_merge($array, $data);
        }
    }

array_splice() 函数从数组中移除选定的元素,并用新元素取代它。该函数也将返回包含被移除元素的数组。

提示:如果函数没有移除任何元素(length=0),则将从 start 参数的位置插入被替换数组(参见例子 2)。
注释:不保留被替换数组中的键名。

 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)
 */

你可能感兴趣的:(向数组中任意位置添加元素实现)