在PHP中任意位置插入数组新项

622

我该如何在数组中的任何位置插入一个新项目,比如在数组中间?


5
可能是如何在特定位置插入数组元素?的重复问题。 - Kashyap Kotak
23个回答

0
如果您只有普通的数组而没有其他特殊需求,那么这个方法就可以使用。请记住,使用array_splice()函数插入元素时,实际上是在开始索引之前插入。移动元素时要小心,因为向上移动意味着$targetIndex -1,而向下移动则意味着$targetIndex + 1。
class someArrayClass
{
    private const KEEP_EXISTING_ELEMENTS = 0;

    public function insertAfter(array $array, int $startIndex, $newElements)
    {
        return $this->insertBefore($array, $startIndex + 1, $newElements);
    }

    public function insertBefore(array $array, int $startIndex, $newElements)
    {
        return array_splice($array, $startIndex, self::KEEP_EXISTING_ELEMENTS, $newElements);
    }
}

0

如果要向具有字符串键的数组中插入元素,可以像这样操作:

/* insert an element after given array key
 * $src = array()  array to work with
 * $ins = array() to insert in key=>array format
 * $pos = key that $ins will be inserted after
 */ 
function array_insert_string_keys($src,$ins,$pos) {

    $counter=1;
    foreach($src as $key=>$s){
        if($key==$pos){
            break;
        }
        $counter++;
    } 

    $array_head = array_slice($src,0,$counter);
    $array_tail = array_slice($src,$counter);

    $src = array_merge($array_head, $ins);
    $src = array_merge($src, $array_tail);

    return($src); 
} 

2
为什么不使用 $src = array_merge($array_head, $ins, $array_tail); 呢? - cartbeforehorse

-3

在经过几天的工作后,这是我能找到的最简单的解决方案。

$indexnumbertoaddat // this is a variable that points to the index # where you 
want the new array to be inserted

$arrayToAdd = array(array('key' => $value, 'key' => $value)); //this is the new 
 array and it's values that you want to add. //the key here is to write it like 
 array(array('key' =>, since you're adding this array inside another array. This 
 is the point that a lot of answer left out. 

array_splice($originalArray, $indexnumbertoaddatt, 0, $arrayToAdd); //the actual 
splice function. You're doing it to $originalArray, at the index # you define, 
0 means you're just shifting all other index items down 1, and then you add the 
new array. 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接