Edw*_*ard 15 php arrays performance
给定一个数组:
$a = array(
'abc',
123,
'k1'=>'v1',
'k2'=>'v2',
78,
'tt',
'k3'=>'v3'
);
Run Code Online (Sandbox Code Playgroud)
由于其内部指针位于其中一个元素上,如何在当前元素之后插入元素?如何在一个知名元素之后插入一个元素,比如'k1'?
表现护理〜
nic*_*ckf 13
您可以通过使用array_keys
和拆分数组来完成它array_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));
Run Code Online (Sandbox Code Playgroud)
我在这里找到了一个很好的答案.我想记录它,所以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;
}
Run Code Online (Sandbox Code Playgroud)