array_splice()用于关联数组

说我有一个关联数组:

array( "color" => "red", "taste" => "sweet", "season" => "summer" ); 

我想介绍一个新的元素:

 "texture" => "bumpy" 

在第二项后面,但保留所有的数组键:

 array( "color" => "red", "taste" => "sweet", "texture" => "bumpy", "season" => "summer" ); 

有没有这样的function? array_splice()不会削减它,它只能使用数字键。

我认为你需要手动做到这一点:

 # Insert at offset 2 $offset = 2; $newArray = array_slice($oldArray, 0, $offset, true) + array('texture' => 'bumpy') + array_slice($oldArray, $offset, NULL, true); 

根据soulmerge的回答,我创build了这个方便的function:

 function array_insert($array,$values,$offset) { return array_slice($array, 0, $offset, true) + $values + array_slice($array, $offset, NULL, true); } 

我讨厌击败一个古老的问题,似乎有人已经拿出了一些类似的答案。 但我想提供一个我认为更彻底的版本。 这个函数被devise为感觉和行为,就像常规的array_splice()一样,包括它的返回值以及它如何处理无效值或负值。 在这方面唯一的区别是,当定义一个replace数组(或string或数字)而不是一个长度,你可以使用空值的长度,而不必传递计数($数组)作为参数。 它会假设从null。 0仍然是0。

函数的唯一区别当然是$ key值参数,指定从哪个关键字开始进行更改。 $ offset已经被留下,现在被用作该初始位置的修饰符。 关键冲突将永远支持replace数组,但也会触发警告。 如果键参数为空或空白,则函数将只查找偏移量参数,其行为与array_splice相同,但保留键值时除外。 如果只是找不到键,那么当array_splice给出的偏移量超出数组长度时,它的行为将与其相同。 它追加到最后。

 /** * Remove or replace elements of an associative array by key value. * @param Object array $input The input associative array * @param string $key The key whose position in the array determines the start of the removed portion. * @param int $offset Adjust the start position derived from the key by this value. * If the sum is positive, it starts from the beginning of the input array. If negative, it starts from the far end. * @param int $length If length is omitted or null, remove everything from key position to the end of the array. * If positive, that many elements will be removed. * If negative, then the end of the removed portion will be that many elements from the end of the array. * @param mixed $replacement Elements from this array will be inserted at the position of the designated key. * @return array Returns the array of the extracted elements. */ function array_splice_assoc(&$input, $key, $offset = 0, $length = null, $replacement = null) { if (!is_array($input)) { $trace = debug_backtrace(); extract($trace[0]); trigger_error( __FUNCTION__."(): expects parameter 1 to be an array, ".gettype($input)." given from $file on line $line", E_USER_WARNING ); return false; } $offset = (int)$offset; $replacement = (array)$replacement; $inputLength = count($input); if (!is_null($key) && $key !== "") { $index = array_search($key, $keys = array_keys($input)); if ($index === false) { $offset = $inputLength; } $offset += $index; } $index = array_search($key, $keys = array_keys($input)); if ($index === false) { $offset = $inputLength; } $offset += $index; if ($offset < 0) { $offset += $inputLength; if ($offset < 0) { $offset = 0; } } if (is_null($length)) { $length = $inputLength; } elseif ($length < 0) { $length += $inputLength - $offset; } $extracted = array_slice($input, $offset, $length, true); $start = array_slice($input, 0, $offset, true); $end = array_slice($input, $offset + $length, $inputLength, true); $remaining = $start + $end; if (count($conflict = array_keys(array_intersect_key($remaining, $replacement)))) { $trace = debug_backtrace(); extract($trace[0]); trigger_error( __FUNCTION__."(): key conflict from $file on line $line", E_USER_WARNING ); foreach ($conflict as $key) { if (isset($start[$key])) { unset($start[$key]); } else { unset($end[$key]); } } } $input = (!empty($replacement)) ? $start + $replacement + $end : $remaining; return $extracted; } 

那么…

 $array1 = array( "fruit1" => "apple", "vegetable1" => "carrot", "vegetable2" => "potato", "fruit2" => "orange", "fruit3" => "banana", "fruit4" => "pear" ); $array2 = array( "snack" => "chips", "vegetable3" => "green bean", "vegetable1" => "corn" ); $vegetables = array_splice_assoc($array1, "fruit1", 1, -3); print_r($array1); print_r($vegetables); array_splice_assoc($array2, "vegetable3", -1, 1, $vegetables); print_r($array2); /* Output is: Array ( [fruit1] => apple [fruit2] => orange [fruit3] => banana [fruit4] => pear ) Array ( [vegetable1] => carrot [vegetable2] => potato ) PHP Warning: array_splice_assoc(): key conflict from /var/www/php/array_splice_assoc.php on line 97 in /var/www/php/array_splice_assoc.php on line 65 Array ( [vegetable1] => carrot [vegetable2] => potato [vegetable3] => green bean ) */ 

这也可以是一个简单的方法来replace单个数组键,同时保持它的位置,而不必经过array_values和array_combine。

 $array3 = array( "vegetable1" => "carrot", "vegetable2" => "potato", "vegetable3" => "tomato", "vegetable4" => "green bean", "vegetable5" => "corn" ); array_splice_assoc($array3, null, 2, 1, array("fruit1" => $array3['vegetable3'])); print_r($array3); /* OUTPUT: Array ( [vegetable1] => carrot [vegetable2] => potato [fruit1] => tomato [vegetable4] => green bean [vegetable5] => corn ) */ 

编辑:我刚刚发现,显然array_merge()不能真正地区分恰好是数字的关联数组键和常规顺序键之间的区别。 使用+操作符而不是array_merge()来合并数组可以避免这个问题。

我不知道是否有一个函数,但你可以遍历你的数组,存储索引,并使用array_push。

那么,你可以从头开始重build数组。 但是以特定顺序通过关联数组的最简单的方法是保持单独的sorting数组。 像这样:

 $order=array('color','taste','texture','season'); foreach($order as $key) { echo $unordered[$key]; } 

这是另一种方式:

 function array_splice_assoc(&$input, $offset, $length = 0, $replacement = array()) { $keys = array_keys($input); $values = array_values($input); array_splice($keys, $offset, $length, array_keys($replacement)); array_splice($values, $offset, $length, array_values($replacement)); $input = array_combine($keys, $values); } 

根据ragulka和soulmerge提供的解决scheme,我创build了一个slightly different function ,让我们指定“键”而不是偏移量。

 <?php /** * Insert values in a associative array at a given position * * @param array $array * The array in which you want to insert * @param array $values * The key => values you want to insert * @param string $pivot * The key position to use as insert position. * @param string $position * Where to insert the values relative to given $position. * Allowed values: 'after' - default or 'before' * * @return array * The resulted array with $values inserted a given position */ function array_insert_at_position($array, $values, $pivot, $position = 'after'){ $offset = 0; foreach($array as $key => $value){ ++$offset; if ($key == $pivot){ break; } } if ($position == 'before'){ --$offset; } return array_slice($array, 0, $offset, TRUE) + $values + array_slice($array, $offset, NULL, TRUE) ; } ?> 

有一个超级简单的方法来做到这一点,我想到了今晚。它将search一个键,像正常拼接,并返回被删除的元素像正常的function。

 function assoc_splice($source_array, $key_name, $length, $replacement){ return array_splice($source_array, array_search($key_name, array_keys($source_array)), $length, $replacement); } 

这工作像array_splice ,但保留插入数组的键:

  function array_splicek(&$array, $offset, $length, $replacement) { if (!is_array($replacement)) { $replacement = array($replacement); } $out = array_slice($array, $offset, $length); $array = array_slice($array, 0, $offset, true) + $replacement + array_slice($array, $offset + $length, NULL, true); return $out; } 

你可以像使用array_splice那样使用它,只需要在最后添加一个k 。 (ragulka的答案是好的,但是这使得更容易适应现有的代码。)所以,例如

 $a = array("color" => "red", "taste" => "sweet", "season" => "summer"); $b = array("texture" => "bumpy"); 

代替

 array_splice($a, 2, 0, $b); 

使用

 array_splicek($a, 2, 0, $b); 

然后$a将包含你正在寻找的结果。

我的解决scheme完全模仿array_splice,第二个参数现在是String $key,而不是Int $offset,

 function array_splice_assoc ( &$input ,$key, $length = 0 , $replacement = null ){ $keys = array_keys( $input ); $offset = array_search( $key, $keys ); if($replacement){ $values = array_values($input); $extracted_elements = array_combine(array_splice($keys, $offset, $length, array_keys($replacement)),array_splice($values, $offset, $length, array_values($replacement))); $input = array_combine($keys, $values); } else { $extracted_elements = array_slice($input, $offset, $length); } return $extracted_elements; } 

所以为了得到结果你需要你会这样做

 $array = array( "color" => "red", "taste" => "sweet", "season" => "summer" ); $replacement = array("texture" => "bumpy"); array_splice_assoc ($array ,"season", 0, $replacement); 

产量

 Array ( [color] => red [taste] => sweet [texture] => bumpy [season] => summer ) 

重要说明:如果密钥不在数组中,则不起作用。

我的解决scheme是(我喜欢使用本地PHP数组函数);

 $startIndex = array_search($firstKey, array_keys($arr); $endIndex = array_search($secondKey, array_keys($arr)); array_splice($arr, $startIndex, $endIndex - $startIndex); 

这很简单,你可以很容易地把它变成一个function。

 function insrt_to_offest($targetArr, $toBeEmbed, $indAfter) { $ind = array_search($indAfter, array_keys($targetArr)); $offset = $ind + 1; # Insert at offset 2 $newArray = array_slice($targetArr, 0, $offset, true) + $toBeEmbed + array_slice($targetArr, $offset, NULL, true); return $newArray; } $features = array( "color" => "red", "taste" => "sweet", "season" => "summer" ); print_r($features); $toBeEmbed = array("texture" => "bumpy"); $newArray = insrt_to_offest($features, $toBeEmbed, 'taste'); print_r($newArray); 

类似于@Luxian的回答,我得到了一个类似的方法,并将其设置为array_splice_key。 https://gist.github.com/4499117

 /** * Insert another array into an associative array after the supplied key * * @param string $key * The key of the array you want to pivot around * @param array $source_array * The 'original' source array * @param array $insert_array * The 'new' associative array to merge in by the key * * @return array $modified_array * The resulting merged arrays */ function array_splice_after_key( $key, $source_array, $insert_array ) { return array_splice_key( $key, $source_array, $insert_array ); } /** * Insert another array into an associative array before the supplied key * * @param string $key * The key of the array you want to pivot around * @param array $source_array * The 'original' source array * @param array $insert_array * The 'new' associative array to merge in by the key * * @return array $modified_array * The resulting merged arrays */ function array_splice_before_key( $key, $source_array, $insert_array ) { return array_splice_key( $key, $source_array, $insert_array, -1 ); } /** * Insert another array into an associative array around a given key * * @param string $key * The key of the array you want to pivot around * @param array $source_array * The 'original' source array * @param array $insert_array * The 'new' associative array to merge in by the key * @param int $direction * Where to insert the new array relative to given $position by $key * Allowed values: positive or negative numbers - default is 1 (insert after $key) * * @return array $modified_array * The resulting merged arrays */ function array_splice_key( $key, $source_array, $insert_array, $direction = 1 ){ $position = array_search( $key, array_keys( $source_array ) ) + $direction; // setup the return with the source array $modified_array = $source_array; if( count($source_array) < $position && $position != 0 ) { // push one or more elements onto the end of array array_push( $modified_array, $insert_array ); } else if ( $position < 0 ){ // prepend one or more elements to the beginning of an array array_unshift( $modified_array, $insert_array ); } else { $modified_array = array_slice($source_array, 0, $position, true) + $insert_array + array_slice($source_array, $position, NULL, true); } return $modified_array; }