當使用 RecursiveIteratorIterator 遞迴遍歷巢狀陣列時,您無法使用 offsetUnset() 或 offsetSet() 修改子陣列的值,除非它們 *全部* 都宣告為 ArrayObject。
(PHP 5, PHP 7, PHP 8)
ArrayObject::offsetUnset — 取消設定指定索引的值
key
要取消設定的索引。
不回傳任何值。
範例 #1 ArrayObject::offsetUnset() 範例
<?php
$arrayobj = new ArrayObject(array(0=>'zero',2=>'two'));
$arrayobj->offsetUnset(2);
var_dump($arrayobj);
?>
以上範例會輸出:
object(ArrayObject)#1 (1) { ["storage":"ArrayObject":private]=> array(1) { [0]=> string(4) "zero" } }
當使用 RecursiveIteratorIterator 遞迴遍歷巢狀陣列時,您無法使用 offsetUnset() 或 offsetSet() 修改子陣列的值,除非它們 *全部* 都宣告為 ArrayObject。
使用集合時要小心。此方法處理的是陣列的參考,而不是其擷取的值。
因此,您可能會犯錯。
為了理解,請查看以下程式碼
<?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
// 首先,建立 Company 物件
$oCompany = new Company();
// 接著,加入 10 個元素
foreach( range(0, 9) as $index )
{
$oCompany->AddEmployee( new Employee() );
}
// 取得它們
$arrEmployee = $oCompany->getEmployeeList();
// 從 "$arrEmployee" 建立一個 ArrayObject
$arrayobject = new ArrayObject($arrEmployee);
// 移除前五個元素
foreach( range(0, 4) as $index )
{
$arrayobject->offsetUnset($index);
}
// 再次取得它們
$arrEmployee = $oCompany->getEmployeeList();
// 它只顯示 5 個元素,它們已透過 "offsetUnset" 方法以引用方式移除
print_r($arrEmployee) ;
?>