简体   繁体   English

PHP ArrayObject插入数组内

[英]PHP ArrayObject insert inside the array

How to insert a new value inside ( *in the middle of the array ) the array of the ArrayObject I know how to do it when it's a plain array, like this: 如何在ArrayObject的数组内部( *在数组的中间 )插入一个新值,我知道当它是一个普通数组时如何做到这一点,如下所示:

$array_1 = array(
            '0' => 'zero',
            '1' => 'one',
            '2' => 'two',
            '3' => 'three',
        );
        echo "<pre>";
        array_splice($array_1, 2, 0, 'more');
        print_r($array_1);

But I don't know if the array is of type object like this: 但是我不知道数组是否是这样的对象类型:

$array_1 = new ArrayObject([  '0' => 'zero',
                '1' => 'one',
                '2' => 'two',
                '3' => 'three']);

Just use append() like this: 像这样使用append()

$array_1 ->append('xy');

This does pretty much the same as $array[] = "xy"; 这和$array[] = "xy";几乎一样$array[] = "xy"; for normal arrays. 对于普通数组。

If you want to replace an arrayObject element just use offsetSet() : 如果要替换arrayObject元素,请使用offsetSet()

$array_1->offsetSet(2, "more");

EDIT: 编辑:

Just use getArrayCopy() then you can use all array functions as you are familiar with: 只需使用getArrayCopy()就可以使用所有熟悉的数组函数:

$array_1 = $array_1->getArrayCopy();
array_splice($array_1, 2, 0, 'more');
$array_1 = new ArrayObject($array_1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM