將unset
函數與SimpleXML解碼數組結合使用時,我發現了一個奇怪的問題。 unset
函數應用於這樣一個數組的索引之一(數字索引),似乎會重置數組索引。在PHP中,在什麼情況下unset()調用會重置數組索引?
這看起來像一個無證的行爲給我(或更像一個錯誤)。有沒有人得到解釋爲什麼SimpleXML數組有一個「特殊reindexing」處理?
下面是一個解釋它的測試案例。
<?php
$a = array(1, 2, 3, 4);
echo "Regular array, before unset(\$a[1]): " . print_r($a, 1);
unset($a[1]);
echo "Regular array, after unset(\$a[1]): " . print_r($a, 1);
$xml = simplexml_load_string(<<<EOT
<?xml version="1.0" encoding="UTF-8"?>
<root>
<node>1</node>
<node>2</node>
<node>3</node>
<node>4</node>
<node>5</node>
</root>
EOT
);
echo "SimpleXML array, before unset(\$a[1]): " . print_r($xml, 1);
unset($xml->node[1]);
echo "SimpleXML array, after unset(\$a[1]): " . print_r($xml, 1);
,我得到的是輸出,
Regular array, before unset($a[1]): Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
Regular array, after unset($a[1]): Array
(
[0] => 1
[2] => 3
[3] => 4
)
SimpleXML array, before unset($a[1]): SimpleXMLElement Object
(
[node] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
)
SimpleXML array, after unset($a[1]): SimpleXMLElement Object
(
[node] => Array
(
[0] => 1
[1] => 3
[2] => 4
[3] => 5
)
)