2009-08-17 25 views

回答

12

您可以通过使用array_keysarray_values拆分阵列来完成,然后将它们拼接起来,然后重新组合。

$insertKey = 'k1'; 

$keys = array_keys($arr); 
$vals = array_values($arr); 

$insertAfter = array_search($insertKey, $keys) + 1; 

$keys2 = array_splice($keys, $insertAfter); 
$vals2 = array_splice($vals, $insertAfter); 

$keys[] = "myNewKey"; 
$vals[] = "myNewValue"; 

$newArray = array_merge(array_combine($keys, $vals), array_combine($keys2, $vals2)); 
+0

此解决方案存在一次性错误。它可以通过添加$ insertAfter ++来纠正;在array_splice()调用之前。 – keithm 2013-03-13 19:58:15

+0

@keithm更新。 – nickf 2013-03-15 09:40:43

1

您不能使用内部数组指针来插入元素。

array_splice它可以插入/删除/替换元素和子阵列,但它的目的是整数索引数组。

恐怕你将不得不重建数组来插入元素(除了要插入第一个元素或最后一个元素的情况)或使用单独的整数索引数组来保存所需顺序的键。

0

这种方式适用于没有密钥的新值。您不能用键插入值,并且数字索引将被重置为0到N-1。

$keys = array_keys($a); 
$index = array_flip($keys); 

$key = key($a); //current element 
//or 
$key = 'k1'; 

array_splice($a, $index[$key] + 1, 0, array('value')); 
1

一般来说,双向链表将是理想的这项任务。

自PHP 5.3以来,有一个内置的实现,名为SplDoublyLinkedList,自PHP 5.5起,它也有add method,允许在中间添加/插入值。

+0

其实,[SplDoublyLinkedList(http://ee.php.net/manual/en/class.spldoublylinkedlist.php)允许插入在[SplDoublyLinkedList :: add方法](http://php.net/manual/en/spldoublylinkedlist.add.php)上的期望索引,因为这[拉请求](https://github.com/php/php-src /拉/ 288)。我不知道这是什么时候添加的,因为文档没有提及哪个php版本改变了。 – Egregore 2015-02-15 10:42:21

+0

它确实提到了版本:(PHP 5> = 5.5.0) - 我已经更新了答案以反映这一点。 – 2015-02-16 06:26:33

2

我发现了一个伟大的答案here的作品真的很好。我想记录它,这样别人就可以SO轻松地找到它:

/* 
* Inserts a new key/value before the key in the array. 
* 
* @param $key 
* The key to insert before. 
* @param $array 
* An array to insert in to. 
* @param $new_key 
* The key to insert. 
* @param $new_value 
* An value to insert. 
* 
* @return 
* The new array if the key exists, FALSE otherwise. 
* 
* @see array_insert_after() 
*/ 
function array_insert_before($key, array &$array, $new_key, $new_value) { 
    if (array_key_exists($key, $array)) { 
    $new = array(); 
    foreach ($array as $k => $value) { 
     if ($k === $key) { 
     $new[$new_key] = $new_value; 
     } 
     $new[$k] = $value; 
    } 
    return $new; 
    } 
    return FALSE; 
} 

/* 
* Inserts a new key/value after the key in the array. 
* 
* @param $key 
* The key to insert after. 
* @param $array 
* An array to insert in to. 
* @param $new_key 
* The key to insert. 
* @param $new_value 
* An value to insert. 
* 
* @return 
* The new array if the key exists, FALSE otherwise. 
* 
* @see array_insert_before() 
*/ 
function array_insert_after($key, array &$array, $new_key, $new_value) { 
    if (array_key_exists ($key, $array)) { 
    $new = array(); 
    foreach ($array as $k => $value) { 
     $new[$k] = $value; 
     if ($k === $key) { 
     $new[$new_key] = $new_value; 
     } 
    } 
    return $new; 
    } 
    return FALSE; 
} 
相关问题