如何在PHP数组中的另一个已知(通过键或指针)元素之后有效地插入元素?

2022-08-31 01:02:07

给定一个数组:

$a = array(
    'abc',
    123,
    'k1'=>'v1',
    'k2'=>'v2',
    78,
    'tt',
    'k3'=>'v3'
);

将其内部指针放在其中一个元素上,如何在当前元素之后插入元素?如何在键已知元素之后插入元素,比如“k1”?

性能护理~


答案 1

您可以通过使用 和 拆分数组来做到这一点,然后将它们两者拼接,然后再次组合它们。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));

答案 2

我在这里找到了一个很好的答案,效果非常好。我想记录它,以便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;
}