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

时间:2010-07-28 14:15:29

标签: php arrays

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

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

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

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

25 个答案:

答案 0 :(得分:188)

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

$res = array_slice($array, 0, 3, true) +
    array("my_key" => "my_value") +
    array_slice($array, 3, count($array)-3, true);

这个例子:

$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);

给出:

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

答案 1 :(得分:92)

对于您的第一个数组,请使用array_splice()

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

array_splice($array_1, 3, 0, 'more');
print_r($array_1);

输出:

Array(
    [0] => zero
    [1] => one
    [2] => two
    [3] => more
    [4] => three
)

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

$array_2['more'] = '2.5';
print_r($array_2);

按照你想要的方式对键进行排序。

答案 2 :(得分: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;
}

示例:

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

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

可能看起来并不完美,但确实有效。

答案 3 :(得分: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));
       }
   }

  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
}

现在您可以使用

测试代码了
//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>";

结果是:

//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
)

答案 4 :(得分:10)

$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));

答案 5 :(得分: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;

    }

用法:

    $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) );

结果:

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
)

答案 6 :(得分:4)

我最近编写了一个函数,用于执行与您尝试的类似的操作,这与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;
}

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

答案 7 :(得分:4)

如果你知道你想要将它插入位置#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;
    }

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

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

答案 8 :(得分:3)

更清洁的方法(基于使用的流动性和更少的代码)。

/**
 * Insert data at position given the target key.
 *
 * @param array $array
 * @param mixed $target_key
 * @param mixed $insert_key
 * @param mixed $insert_val
 * @param bool $insert_after
 * @param bool $append_on_fail
 * @param array $out
 * @return array
 */
function array_insert(
    array $array, 
    $target_key, 
    $insert_key, 
    $insert_val = null,
    $insert_after = true,
    $append_on_fail = false,
    $out = [])
{
    foreach ($array as $key => $value) {
        if ($insert_after) $out[$key] = $value;
        if ($key == $target_key) $out[$insert_key] = $insert_val;
        if (!$insert_after) $out[$key] = $value;
    }

    if (!isset($array[$target_key]) && $append_on_fail) {
        $out[$insert_key] = $insert_val;
    }

    return $out;
}

用法:

$colors = [
    'blue' => 'Blue',
    'green' => 'Green',
    'orange' => 'Orange',
];

$colors = array_insert($colors, 'blue', 'pink', 'Pink');

die(var_dump($colors));

答案 9 :(得分:2)

非常简单的2字符串回答您的问题:

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

首先,使用array_splice将任何内容插入第三个元素,然后为该元素分配一个值:

array_splice($array_1, 3, 0 , true);
$array_1[3] = array('sample_key' => 'sample_value');

答案 10 :(得分:2)

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

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;
}

所以,如果你有:

$array = [
    'one' => 1,
    'three' => 3
];
$array_to_insert = ['two' => 2];

执行:

$result_array = array_splice_after_key($array, 'one', $array_to_insert);

你将拥有:

Array ( 
    ['one'] => 1 
    ['two'] => 2 
    ['three'] => 3 
)

答案 11 :(得分:1)

这是如何在某个位置插入项目数组的更好方法。

function arrayInsert($array, $item, $position)
{
    $begin = array_slice($array, 0, $position);
    array_push($begin, $item);
    $end = array_slice($array, $position);
    $resultArray = array_merge($begin, $end);
    return $resultArray;
}

答案 12 :(得分:1)

这是PHP 7.1

中的另一个解决方案

     /**
     * @param array $input    Input array to add items to
     * @param array $items    Items to insert (as an array)
     * @param int   $position Position to inject items from (starts from 0)
     *
     * @return array
     */
    function arrayInject( array $input, array $items, int $position ): array 
    {
        if (0 >= $position) {
            return array_merge($items, $input);
        }
        if ($position >= count($input)) {
            return array_merge($input, $items);
        }

        return array_merge(
            array_slice($input, 0, $position, true),
            $items,
            array_slice($input, $position, null, true)
        );
    }

答案 13 :(得分:1)

我刚刚创建了一个ArrayHelper类,这使得数字索引非常容易。

class ArrayHelper
{
    /*
        Inserts a value at the given position or throws an exception if
        the position is out of range.
        This function will push the current values up in index. ex. if 
        you insert at index 1 then the previous value at index 1 will 
        be pushed to index 2 and so on.
        $pos: The position where the inserted value should be placed. 
        Starts at 0.
    */
    public static function insertValueAtPos(array &$array, $pos, $value) {
        $maxIndex = count($array)-1;

        if ($pos === 0) {
            array_unshift($array, $value);
        } elseif (($pos > 0) && ($pos <= $maxIndex)) {
            $firstHalf = array_slice($array, 0, $pos);
            $secondHalf = array_slice($array, $pos);
            $array = array_merge($firstHalf, array($value), $secondHalf);
        } else {
            throw new IndexOutOfBoundsException();
        }

    }
}

示例:

$array = array('a', 'b', 'c', 'd', 'e');
$insertValue = 'insert';
\ArrayHelper::insertValueAtPos($array, 3, $insertValue);

开始$ array:

Array ( 
    [0] => a 
    [1] => b 
    [2] => c 
    [3] => d 
    [4] => e 
)

结果:

Array ( 
    [0] => a 
    [1] => b 
    [2] => c 
    [3] => insert 
    [4] => d 
    [5] => e 
)

答案 14 :(得分:1)

使用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);

答案 15 :(得分:1)

我需要能够在键之前插入,替换之后的东西;如果找不到目标键,则在数组的开头或结尾添加。默认是在密钥后插入。

新功能

/**
 * Insert element into an array at a specific key.
 *
 * @param array $input_array
 *   The original array.
 * @param array $insert
 *   The element that is getting inserted; array(key => value).
 * @param string $target_key
 *   The key name.
 * @param int $location
 *   1 is after, 0 is replace, -1 is before.
 *
 * @return array
 *   The new array with the element merged in.
 */
function insert_into_array_at_key(array $input_array, array $insert, $target_key, $location = 1) {
  $output = array();
  $new_value = reset($insert);
  $new_key = key($insert);
  foreach ($input_array as $key => $value) {
    if ($key === $target_key) {
      // Insert before.
      if ($location == -1) {
        $output[$new_key] = $new_value;
        $output[$key] = $value;
      }
      // Replace.
      if ($location == 0) {
        $output[$new_key] = $new_value;
      }
      // After.
      if ($location == 1) {
        $output[$key] = $value;
        $output[$new_key] = $new_value;
      }
    }
    else {
      // Pick next key if there is an number collision.
      if (is_numeric($key)) {
        while (isset($output[$key])) {
          $key++;
        }
      }
      $output[$key] = $value;
    }
  }
  // Add to array if not found.
  if (!isset($output[$new_key])) {
    // Before everything.
    if ($location == -1) {
      $output = $insert + $output;
    }
    // After everything.
    if ($location == 1) {
      $output[$new_key] = $new_value;
    }

  }
  return $output;
}

输入代码

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

$array_1 = insert_into_array_at_key($array_1, array('sample_key' => 'sample_value'), 2, 1);
print_r($array_1);
$array_2 = insert_into_array_at_key($array_2, array('sample_key' => 'sample_value'), 'two', 1);
print_r($array_2);

输出

Array
(
    [0] => zero
    [1] => one
    [2] => two
    [sample_key] => sample_value
    [3] => three
)
Array
(
    [zero] => 0
    [one] => 1
    [two] => 2
    [sample_key] => sample_value
    [three] => 3
)

答案 16 :(得分:1)

这是一个古老的问题,但我在2014年发表了评论,并经常回到此问题。我以为我会留下一个完整的答案。这不是最短的解决方案,但很容易理解。

将新值插入到关联数组中,该数组位于编号位置,保留键和保留顺序。

import logging
import os
import time
import datetime
import json
import azure.functions as func


def main(req: func.HttpRequest,context: func.Context) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    t = datetime.datetime.now().strftime("%H-%M-%S-%f")
    foldername=context.function_directory+"/newfolder"+t
    os.makedirs(foldername)
    suffix = ".txt"
    newfile= t+suffix
    os.getcwd()
    os.chdir(foldername)
    if not os.path.exists(newfile):
        f = open(newfile,'w')
        f.write("test")
        f.close()
    data=[]
    for filename in os.listdir(context.function_directory):
        print(filename)
        d1={"filename":filename}
        data.append(d1)
    jsondata=json.dumps(data)


    return func.HttpResponse(jsondata)

答案 17 :(得分:0)

试试这个 ===

$key_pos=0;
$a1=array("a"=>"red", "b"=>"green", "c"=>"blue", "d"=>"yellow");
$arrkey=array_keys($a1);
array_walk($arrkey,function($val,$key) use(&$key_pos) {
  if($val=='b')
    {
        $key_pos=$key;
    }
  });
$a2=array("e"=>"purple");
$newArray = array_slice($a1, 0, $key_pos, true) + $a2 +
        array_slice($a1, $key_pos, NULL, true);
print_r($newArray);

输出

Array (
      [a] => red
      [e] => purple
      [b] => green
      [c] => blue
      [d] => yellow )

答案 18 :(得分:0)

这可以通过 array.splice() 来完成。请注意 array_splice 或 array_merge 不保留关联数组的键。因此使用了array_slice,并使用'+'运算符来连接两个数组。

更多详情here



$array_1 = array(
    '0' => 'zero',
    '1' => 'one',
    '2' => 'two',
    '3' => 'three',
  );
  
  $array_2 = array(
    'zero'  => '0',
    'one'   => '1',
    'two'   => '2',
    'three' => '3',
  );
  $index = 2;
  $finalArray = array_slice($array_1, 0, $index, true) +
                $array2  +
                array_slice($array_2, $index, NULL, true);
print_r($finalArray);
/*
Array
(
    [0] => zero
    [1] => one
    [10] => grapes
    [z] => mangoes
    [two] => 2
    [three] => 3
)
*/




答案 19 :(得分:0)

这是我的版本:

/**
 * 
 * Insert an element after an index in an array
 * @param array $array  
 * @param string|int $key 
 * @param mixed $value
 * @param string|int $offset
 * @return mixed
 */
function array_splice_associative($array, $key, $value, $offset) {
    if (!is_array($array)) {
        return $array;
    }
    if (array_key_exists($key, $array)) {
        unset($array[$key]);
    }
    $return = array();
    $inserted = false;
    foreach ($array as $k => $v) {
        $return[$k] = $v;
        if ($k == $offset && !$inserted) {
            $return[$key] = $value;
            $inserted = true;
        }
    }
    if (!$inserted) {
        $return[$key] = $value;
    }


    return $return;
}

答案 20 :(得分:0)

如果您只想将某个项目插入某个位置的数组中(基于@clausvdb答案):

function array_insert($arr, $insert, $position) {
    $i = 0;
    $ret = array();
    foreach ($arr as $key => $value) {
            if ($i == $position) {
                $ret[] = $insert;
            }
            $ret[] = $value;
            $i++;
    }
    return $ret;
}

答案 21 :(得分:0)

不像Artefacto那样具体,但基于他使用array_slice()的建议,我编写了下一个函数:

function arrayInsert($target, $byKey, $byOffset, $valuesToInsert, $afterKey) {
    if (isset($byKey)) {
        if (is_numeric($byKey)) $byKey = (int)floor($byKey);
        $offset = 0;

        foreach ($target as $key => $value) {
            if ($key === $byKey) break;
            $offset++;
        }

        if ($afterKey) $offset++;
    } else {
        $offset = $byOffset;
    }

    $targetLength = count($target);
    $targetA = array_slice($target, 0, $offset, true);
    $targetB = array_slice($target, $offset, $targetLength, true);
    return array_merge($targetA, $valuesToInsert, $targetB);
}

特点:

  • 插入一个或多个值
  • 插入键值对
  • 在键之前/之后插入,或通过偏移
  • 插入

用法示例:

$target = [
    'banana' => 12,
    'potatoe' => 6,
    'watermelon' => 8,
    'apple' => 7,
    2 => 21,
    'pear' => 6
];

// Values must be nested in an array
$insertValues = [
    'orange' => 0,
    'lemon' => 3,
    3
];

// By key
// Third parameter is not applicable
//     Insert after 2 (before 'pear')
var_dump(arrayInsert($target, 2, null, $valuesToInsert, true));
//     Insert before 'watermelon'
var_dump(arrayInsert($target, 'watermelon', null, $valuesToInsert, false)); 

// By offset
// Second and last parameter are not applicable
//     Insert in position 2 (zero based i.e. before 'watermelon')
var_dump(arrayInsert($target, null, 2, $valuesToInsert, null)); 

答案 22 :(得分:-1)

我这样做

$slightly_damaged = array_merge(array_slice($slightly_damaged, 0, 4, true) + array("4" => "0.0"), array_slice($slightly_damaged, 4, count($slightly_damaged)-4, true));

致谢。

答案 23 :(得分:-1)

您可以在 foreach循环期间插入元素,因为该循环适用于原始数组的副本,但是您必须跟踪插入的行数(我将此代码称为“膨胀”)

$bloat=0;
foreach ($Lines as $n=>$Line)
    {
    if (MustInsertLineHere($Line))
        {
        array_splice($Lines,$n+$bloat,0,"string to insert");
        ++$bloat;
        }
    }

很明显,您可以推广这种“膨胀”的想法,以处理在foreach循环中的任意插入和删除。

答案 24 :(得分:-1)

简便的方法..使用array_splice()

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

$addArray = array('sample_key' => 'sample_value');

array_splice($rs, 3, 0, $addArray);

结果..

Array
(
    [0] => zero
    [1] => one
    [2] => two
    [3] => sample_value
    [4] => three
)