When traversing recursively nested arrays using an RecursiveIteratorIterator, you cannot offsetUnset() or offsetSet() sub-array values, unless they are *all* declared as ArrayObject.
ArrayObject::offsetUnset
(PHP 5 >= 5.0.0)
ArrayObject::offsetUnset — Destruye el valor para el índice especificado
Descripción
Destruir el valor para el índice especificado.
Parámetros
-
index -
El índice a ser destruido.
Valores devueltos
No devuelve ningún valor.
Ejemplos
Ejemplo #1 Ejemplo de ArrayObject::offsetUnset()
<?php
$arrayobj = new ArrayObject(array(0=>'cero',2=>'dos'));
$arrayobj->offsetUnset(2);
var_dump($arrayobj);
?>
El resultado del ejemplo sería:
object(ArrayObject)#1 (1) {
[0]=>
string(4) "cero"
}
pvenakis at efront dot gr ¶
5 years ago
oalexandrino at yahoo dot com dot br ¶
5 years ago
Be careful when you are working with collections. This method works with the reference of an array instead of its retrieved value.
So, you can do a mistake.
In order to understand have a look at code as follow:
<?php
class Employee
{
public function __construct()
{
}
}
class Company
{
private $arrEmployee;
public function __construct()
{
}
public function AddEmployee(Employee $oEmployee)
{
$this->arrEmployee[] = $oEmployee;
}
public function getEmployeeList()
{
return $this->arrEmployee;
}
}
?>
<?php
// first, creates the Company object
$oCompany = new Company();
// second, add 10 elements in
foreach( range(0, 9) as $index )
{
$oCompany->AddEmployee( new Employee() );
}
// get them
$arrEmployee = $oCompany->getEmployeeList();
// creates an ArrayObject from "$arrEmployee"
$arrayobject = new ArrayObject($arrEmployee);
// unsets its firt five elements
foreach( range(0, 4) as $index )
{
$arrayobject->offsetUnset($index);
}
// get them again
$arrEmployee = $oCompany->getEmployeeList();
// it shows just 5 elements, they were removed as reference via "offsetUnset" method
print_r($arrEmployee) ;
?>
