如何在特定位置将元素插入数组?

Kir*_*lla 171 php arrays

让我们假设我们有两个数组:

$array_1 = array(
  '0' => 'zero',
  '1' => 'one',
  '2' => 'two',
  '3' => 'three',
);

$array_2 = array(
  'zero'  => '0',
  'one'   => '1',
  'two'   => '2',
  'three' => '3',
);
Run Code Online (Sandbox Code Playgroud)

现在,我想插入array('sample_key' => 'sample_value')每个数组的第三个元素之后.我该怎么做?

Art*_*cto 198

array_slice()可用于提取数组的部分,联合数组operator(+)可以重新组合这些部分.

$res = array_slice($array, 0, 3, true) +
    array("my_key" => "my_value") +
    array_slice($array, 3, count($array)-3, true);
Run Code Online (Sandbox Code Playgroud)

这个例子:

$array = array(
  'zero'  => '0',
  'one'   => '1',
  'two'   => '2',
  'three' => '3',
);
$res = array_slice($array, 0, 3, true) +
    array("my_key" => "my_value") +
    array_slice($array, 3, count($array) - 1, true) ;
print_r($res);
Run Code Online (Sandbox Code Playgroud)

得到:

Array
(
    [zero] => 0
    [one] => 1
    [two] => 2
    [my_key] => my_value
    [three] => 3
)

  • 不应该使用`+`!请使用`array_merge`代替!因为如果索引是整数(正常数组,而不是散列),`+`将无法按预期工作! (27认同)
  • 而不是使用`count($ array)-3`,你可以简单地将null指定为相同的效果.此外,使用`array_merge`作为TMS建议不要求您使用唯一索引.示例:将"new-value"添加到现有数组:`$ b = array_merge(array_slice($ a,0,1,true),array('new-value'),array_slice($ a,1,null,true ));` (10认同)
  • 您应该使用array_splice()作为M42建议.它只用一行代码解决了这个问题. (7认同)
  • @ M42它解决了*a*问题; 不是OP问的人. (4认同)
  • @Tomas是否按预期工作取决于您的期望.`array_merge`关于数字键的行为不适合这个问题. (4认同)
  • 关于 `+` 和 `array_merge` 似乎有些混淆。如果您想将内容插入数值数组,则不应使用 `+`,因为它可能与您的期望不符。但是你也不应该使用`array_merge`;对于数值数组,整个问题都可以通过 [`array_splice`](http://php.net/array_splice) 函数解决。对于关联或混合数组,您可能不希望重新索引数字键,因此使用 `+` 是完全合适的。 (2认同)

Tot*_*oto 96

对于您的第一个阵列,请使用array_splice():

$array_1 = array(
  '0' => 'zero',
  '1' => 'one',
  '2' => 'two',
  '3' => 'three',
);

array_splice($array_1, 3, 0, 'more');
print_r($array_1);
Run Code Online (Sandbox Code Playgroud)

输出:

Array(
    [0] => zero
    [1] => one
    [2] => two
    [3] => more
    [4] => three
)
Run Code Online (Sandbox Code Playgroud)

对于第二个没有订单,所以你只需要这样做:

$array_2['more'] = '2.5';
print_r($array_2);
Run Code Online (Sandbox Code Playgroud)

并根据您的需要对键进行排序.

  • 第二个数组确实有一个订单...所有数组都有,因为它们也是双链表. (30认同)
  • -1,如上所述"没有订单"是假的.此外,array_splice破坏了第一个示例中的键/值关联(但可能是OP意图). (4认同)
  • +1好一点,第二个数组是无序的。 (2认同)
  • 事实上,PHP中的@Artefacto"Arrays"是_ordered哈希表_.PHP数组就像数组一样,但它们永远不是真正的数组; 它们也不是链表或数组列表. (2认同)

cla*_*vdb 19

码:

function insertValueAtPosition($arr, $insertedArray, $position) {
    $i = 0;
    $new_array=[];
    foreach ($arr as $key => $value) {
        if ($i == $position) {
            foreach ($insertedArray as $ikey => $ivalue) {
                $new_array[$ikey] = $ivalue;
            }
        }
        $new_array[$key] = $value;
        $i++;
    }
    return $new_array;
}
Run Code Online (Sandbox Code Playgroud)

例:

$array        = ["A"=8, "K"=>3];
$insert_array = ["D"= 9];

insertValueAtPosition($array, $insert_array, $position=2);
// result ====> ["A"=>8,  "D"=>9,  "K"=>3];
Run Code Online (Sandbox Code Playgroud)

可能看起来不太完美,但它确实有效.

  • 你基本上是想拼接,不要重新发明轮子. (10认同)
  • 不,他没有重新发明轮子.array_splice()不允许输入键和值.仅将特定位置的值作为键. (10认同)

Moh*_*aid 13

这是一个你可以使用的简单功能.只需插上游戏即可.

这是按索引插入,而不是按值插入.

您可以选择传递数组,也可以使用已经声明的数组.

编辑:更短的版本:

   function insert($array, $index, $val)
   {
       $size = count($array); //because I am going to use this more than one time
       if (!is_int($index) || $index < 0 || $index > $size)
       {
           return -1;
       }
       else
       {
           $temp   = array_slice($array, 0, $index);
           $temp[] = $val;
           return array_merge($temp, array_slice($array, $index, $size));
       }
   }
Run Code Online (Sandbox Code Playgroud)
  function insert($array, $index, $val) { //function decleration
    $temp = array(); // this temp array will hold the value 
    $size = count($array); //because I am going to use this more than one time
    // Validation -- validate if index value is proper (you can omit this part)       
        if (!is_int($index) || $index < 0 || $index > $size) {
            echo "Error: Wrong index at Insert. Index: " . $index . " Current Size: " . $size;
            echo "<br/>";
            return false;
        }    
    //here is the actual insertion code
    //slice part of the array from 0 to insertion index
    $temp = array_slice($array, 0, $index);//e.g index=5, then slice will result elements [0-4]
    //add the value at the end of the temp array// at the insertion index e.g 5
    array_push($temp, $val);
    //reconnect the remaining part of the array to the current temp
    $temp = array_merge($temp, array_slice($array, $index, $size)); 
    $array = $temp;//swap// no need for this if you pass the array cuz you can simply return $temp, but, if u r using a class array for example, this is useful. 

     return $array; // you can return $temp instead if you don't use class array
}
Run Code Online (Sandbox Code Playgroud)

现在您可以使用测试代码了

//1
$result = insert(array(1,2,3,4,5),0, 0);
echo "<pre>";
echo "<br/>";
print_r($result);
echo "</pre>";
//2
$result = insert(array(1,2,3,4,5),2, "a");
echo "<pre>";
print_r($result);
echo "</pre>";
//3
$result = insert(array(1,2,3,4,5) ,4, "b");
echo "<pre>";
print_r($result);
echo "</pre>";
//4
$result = insert(array(1,2,3,4,5),5, 6);
echo "<pre>";
echo "<br/>";
print_r($result);
echo "</pre>";
Run Code Online (Sandbox Code Playgroud)

结果是:

//1
Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
)
//2
Array
(
    [0] => 1
    [1] => 2
    [2] => a
    [3] => 3
    [4] => 4
    [5] => 5
)
//3
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => b
    [5] => 5
)

//4
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)
Run Code Online (Sandbox Code Playgroud)


小智 11

$list = array(
'Tunisia' => 'Tunis',
'Germany' => 'Berlin',
'Italy' => 'Rom',
'Egypt' => 'Cairo'
);
$afterIndex = 2;
$newVal= array('Palestine' => 'Jerusalem');

$newList = array_merge(array_slice($list,0,$afterIndex+1), $newVal,array_slice($list,$afterIndex+1));
Run Code Online (Sandbox Code Playgroud)


Vil*_*los 6

最简单的解决方案,如果您想在某个键后插入(元素或数组):

function array_splice_after_key($array, $key, $array_to_insert)
{
    $key_pos = array_search($key, array_keys($array));
    if($key_pos !== false){
        $key_pos++;
        $second_array = array_splice($array, $key_pos);
        $array = array_merge($array, $array_to_insert, $second_array);
    }
    return $array;
}
Run Code Online (Sandbox Code Playgroud)

所以,如果你有:

$array = [
    'one' => 1,
    'three' => 3
];
$array_to_insert = ['two' => 2];
Run Code Online (Sandbox Code Playgroud)

并执行:

$result_array = array_splice_after_key($array, 'one', $array_to_insert);
Run Code Online (Sandbox Code Playgroud)

你将拥有:

Array ( 
    ['one'] => 1 
    ['two'] => 2 
    ['three'] => 3 
)
Run Code Online (Sandbox Code Playgroud)


Pet*_*han 5

我最近编写了一个函数来执行类似于您正在尝试的操作,它与 clasvdb 的答案类似。

function magic_insert($index,$value,$input_array ) {
  if (isset($input_array[$index])) {
    $output_array = array($index=>$value);
    foreach($input_array as $k=>$v) {
      if ($k<$index) {
        $output_array[$k] = $v;
      } else {
        if (isset($output_array[$k]) ) {
          $output_array[$k+1] = $v;
        } else {
          $output_array[$k] = $v;
        }
      } 
    }

  } else {
    $output_array = $input_array;
    $output_array[$index] = $value;
  }
  ksort($output_array);
  return $output_array;
}
Run Code Online (Sandbox Code Playgroud)

基本上它会在特定点插入,但通过向下移动所有项目来避免覆盖。


Tom*_*ger 5

如果你不知道你想把它插入到位置#3,但你知道你想在后面插入它的键,我在看到这个问题后编写了这个小函数。

/**
     * Inserts any number of scalars or arrays at the point
     * in the haystack immediately after the search key ($needle) was found,
     * or at the end if the needle is not found or not supplied.
     * Modifies $haystack in place.
     * @param array &$haystack the associative array to search. This will be modified by the function
     * @param string $needle the key to search for
     * @param mixed $stuff one or more arrays or scalars to be inserted into $haystack
     * @return int the index at which $needle was found
     */                         
    function array_insert_after(&$haystack, $needle = '', $stuff){
        if (! is_array($haystack) ) return $haystack;

        $new_array = array();
        for ($i = 2; $i < func_num_args(); ++$i){
            $arg = func_get_arg($i);
            if (is_array($arg)) $new_array = array_merge($new_array, $arg);
            else $new_array[] = $arg;
        }

        $i = 0;
        foreach($haystack as $key => $value){
            ++$i;
            if ($key == $needle) break;
        }

        $haystack = array_merge(array_slice($haystack, 0, $i, true), $new_array, array_slice($haystack, $i, null, true));

        return $i;
    }
Run Code Online (Sandbox Code Playgroud)

这是一个键盘小提琴,可以看到它的实际效果:http ://codepad.org/5WlKFKfz

注意: array_splice() 比 array_merge(array_slice()) 效率更高,但插入数组的键会丢失。叹。


Déj*_*dić 5

此功能支持:

  • 数字键和关键键
  • 在创建密钥之前或之后插入
  • 如果未建立密钥,则附加到数组的末尾

function insert_into_array( $array, $search_key, $insert_key, $insert_value, $insert_after_founded_key = true, $append_if_not_found = false ) {

        $new_array = array();

        foreach( $array as $key => $value ){

            // INSERT BEFORE THE CURRENT KEY? 
            // ONLY IF CURRENT KEY IS THE KEY WE ARE SEARCHING FOR, AND WE WANT TO INSERT BEFORE THAT FOUNDED KEY
            if( $key === $search_key && ! $insert_after_founded_key )
                $new_array[ $insert_key ] = $insert_value;

            // COPY THE CURRENT KEY/VALUE FROM OLD ARRAY TO A NEW ARRAY
            $new_array[ $key ] = $value;

            // INSERT AFTER THE CURRENT KEY? 
            // ONLY IF CURRENT KEY IS THE KEY WE ARE SEARCHING FOR, AND WE WANT TO INSERT AFTER THAT FOUNDED KEY
            if( $key === $search_key && $insert_after_founded_key )
                $new_array[ $insert_key ] = $insert_value;

        }

        // APPEND IF KEY ISNT FOUNDED
        if( $append_if_not_found && count( $array ) == count( $new_array ) )
            $new_array[ $insert_key ] = $insert_value;

        return $new_array;

    }
Run Code Online (Sandbox Code Playgroud)

用法:

    $array1 = array(
        0 => 'zero',
        1 => 'one',
        2 => 'two',
        3 => 'three',
        4 => 'four'
    );

    $array2 = array(
        'zero'  => '# 0',
        'one'   => '# 1',
        'two'   => '# 2',
        'three' => '# 3',
        'four'  => '# 4'
    );

    $array3 = array(
        0 => 'zero',
        1 => 'one',
       64 => '64',
        3 => 'three',
        4 => 'four'
    );


    // INSERT AFTER WITH NUMERIC KEYS
    print_r( insert_into_array( $array1, 3, 'three+', 'three+ value') );

    // INSERT AFTER WITH ASSOC KEYS
    print_r( insert_into_array( $array2, 'three', 'three+', 'three+ value') );

    // INSERT BEFORE
    print_r( insert_into_array( $array3, 64, 'before-64', 'before-64 value', false) );

    // APPEND IF SEARCH KEY ISNT FOUNDED
    print_r( insert_into_array( $array3, 'undefined assoc key', 'new key', 'new value', true, true) );
Run Code Online (Sandbox Code Playgroud)

结果:

Array
(
    [0] => zero
    [1] => one
    [2] => two
    [3] => three
    [three+] => three+ value
    [4] => four
)
Array
(
    [zero] => # 0
    [one] => # 1
    [two] => # 2
    [three] => # 3
    [three+] => three+ value
    [four] => # 4
)
Array
(
    [0] => zero
    [1] => one
    [before-64] => before-64 value
    [64] => 64
    [3] => three
    [4] => four
)
Array
(
    [0] => zero
    [1] => one
    [64] => 64
    [3] => three
    [4] => four
    [new key] => new value
)
Run Code Online (Sandbox Code Playgroud)


小智 5

使用 array_splice 代替 array_slice 可以减少一次函数调用。

$toto =  array(
  'zero'  => '0',
  'one'   => '1',
  'two'   => '2',
  'three' => '3'
);
$ret = array_splice($toto, 3 );
$toto = $toto +  array("my_key" => "my_value") + $ret;
print_r($toto);
Run Code Online (Sandbox Code Playgroud)