在PHP中向数组中的任意位置插入新项
一个可以在整数和字符串位置插入的函数:
/** * @param array $array * @param int|string $position * @param mixed $insert */ function array_insert(&$array, $position, $insert) { if (is_int($position)) { array_splice($array, $position, 0, $insert); } else { $pos = array_search($position, array_keys($array)); $array = array_merge( array_slice($array, 0, $pos), $insert, array_slice($array, $pos) ); } }
整数用法:
$arr = ["one", "two", "three"]; array_insert( $arr, 1, "one-half" ); // -> array ( 0 => 'one', 1 => 'one-half', 2 => 'two', 3 => 'three', )
字符串用法:
$arr = [ "name" => [ "type" => "string", "maxlength" => "30", ], "email" => [ "type" => "email", "maxlength" => "150", ], ]; array_insert( $arr, "email", [ "phone" => [ "type" => "string", "format" => "phone", ], ] ); // -> array ( 'name' => array ( 'type' => 'string', 'maxlength' => '30', ), 'phone' => array ( 'type' => 'string', 'format' => 'phone', ), 'email' => array ( 'type' => 'email', 'maxlength' => '150', ), )
你可能会觉得这更加直观。它只需要调用一个函数:array_splice
:
$original = array( 'a', 'b', 'c', 'd', 'e' ); $inserted = array( 'x' ); // not necessarily an array, see manual quote array_splice( $original, 3, 0, $inserted ); // splice in at position 3 // $original is now a b c x d e
如果替换只是一个元素,则不必将array()放在其周围,除非该元素本身是数组、对象或NULL。
返回值:需要注意的是,该函数不会返回所需的替换。原始数组
$original
通过引用传递,并在原地编辑。请参见参数列表
中带有&
的表达式array &$array
。