Domanda

Si consideri un semplice PHP ArrayObject con due elementi.

$ao = new ArrayObject();
$ao[] = 'a1';  // [0] => a1
$ao[] = 'a2';  // [1] => a2

Quindi eliminare l'ultimo elemento e aggiungere un nuovo elemento.

$ao->offsetUnset(1);
$ao[] = 'a3';  // [2] => a3

mi piacerebbe molto simile per essere in grado di avere 'A3' essere [1].

Come faccio a ripristinare il valore del puntatore interno prima aggiungo 'A3'?

Ho una funzione semplice che fa questo ma non mi piacerebbe copiare l'array se non ho a.

function array_collapse($array) {
    $return = array();
    while ($a = current($array)) {
        $return[] = $a;
        next($array);
    }
    return $return;
}
È stato utile?

Soluzione

Con l'espansione sulla questione nelle vostre osservazioni: che avrebbe dovuto estendere la classe ArrayObject per ottenere questo tipo di comportamento:

class ReindexingArray extends ArrayObject {
    function offsetUnset($offset){
        parent::offsetUnset($offset);
        $this->exchangeArray(array_values($this->getArrayCopy()));
    }
    //repeat for every other function altering the values.
}

Un'altra opzione sarebbe la SplDoublyLinkedList:

<?php
$u = new SplDoublyLinkedList();
$array = array('1' => 'one',
               '2' => 'two',
               '3' => 'three');
foreach($array as $value) $u[] = $value;
var_dump($u);
unset($u[1]);        
var_dump($u);
$u[] = 'another thing';
var_dump($u);

Altri suggerimenti

Perché non usare offsetSet :

$ao = new ArrayObject();
$ao[] = 'a1';  // [0] => a1
$ao[] = 'a2';  // [1] => a2
$ao->offsetUnset(1);
$ao->offsetSet(1, 'a3');

Questo è un po 'stupido, ma si può lanciare a matrice e l'uso standard array_splice su di esso:

$ao = new ArrayObject();
$ao[] = 'element 1';
$ao[] = 'element 2';
$ao[] = 'element 3';
$ao[] = 'element 4';

var_dump($ao);

$items = (array) $ao;
array_splice($items, 1, 2);
$ao = new ArrayObject($items);
$ao[] = 'element 5';

var_dump($ao);

Questo si traduce in:

object(ArrayObject)#1 (1) {
  ["storage":"ArrayObject":private]=>
  array(4) {
    [0]=>
    string(9) "element 1"
    [1]=>
    string(9) "element 2"
    [2]=>
    string(9) "element 3"
    [3]=>
    string(9) "element 4"
  }
}
object(ArrayObject)#2 (1) {
  ["storage":"ArrayObject":private]=>
  array(3) {
    [0]=>
    string(9) "element 1"
    [1]=>
    string(9) "element 4"
    [2]=>
    string(9) "element 5"
  }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top