简体   繁体   中英

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:

$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:

$array_1 ->append('xy');

This does pretty much the same as $array[] = "xy"; for normal arrays.

If you want to replace an arrayObject element just use offsetSet() :

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

EDIT:

Just use getArrayCopy() then you can use all array functions as you are familiar with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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