2009-08-17 27 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; 
} 
相關問題