[英]How to reset array index after unset key in foreach loop in php?
[英]How to unset object key by accessing it in loop array of hierarchical keys (php)
我有一個 XML 對象
$xml = SimpleXMLElement Object
(
[a] => SimpleXMLElement Object
(
[b] => SimpleXMLElement Object
(
[c] => 'hey',
),
),
)
現在,我將所有鍵都放在數組中,我想取消設置最后一個鍵,即對象中的“c”
$temp = $xml;
$keys_arr = ['a', 'b', 'c'];
foreach($keys_arr => $key){
$temp = $temp->$key;
}
unset($temp) // I want this to work like when we use this 'unset($xml->a->b->c);'
當我們打印 $temp 時:
print_r($temp);
輸出應該是:
SimpleXMLElement Object
(
[a] => SimpleXMLElement Object
(
[b] => SimpleXMLElement Object
(
// without '[c]' key
),
),
)
這是一種遞歸方法(與堆疊相反):
代碼:(演示)
function recurse(&$object,$keys){ // modify the input by reference
$key=array_shift($keys);
if(isset($object->$key)){ // avoid trouble
if(empty($keys)){
unset($object->$key); // remove at last key
}else{
recurse($object->$key,$keys); // continue recursion
}
}
}
$xmlstring=<<<XML
<root>
<a>
<b>
<c>hey</c>
</b>
</a>
</root>
XML;
$keys=['a','b','c'];
$xml=new SimpleXMLElement($xmlstring);
echo "Before: \n";
var_export($xml);
echo "\n----\nAfter:\n";
recurse($xml,$keys); // modify input
var_export($xml);
輸出:
Before:
SimpleXMLElement::__set_state(array(
'a' =>
SimpleXMLElement::__set_state(array(
'b' =>
SimpleXMLElement::__set_state(array(
'c' => 'hey',
)),
)),
))
----
After:
SimpleXMLElement::__set_state(array(
'a' =>
SimpleXMLElement::__set_state(array(
'b' =>
SimpleXMLElement::__set_state(array(
)),
)),
))
這是我如何堆疊它以達到相同的結果: Demo
$mod=&$xml; // modify $xml by reference
$keys=['a','b','c'];
$last=array_pop($keys); // assuming the array will not be empty, the array will contain valid/existing object keys
foreach($keys as $key){ // iterate/traverse all remaining keys (e.g. 'a','b' because 'c' was popped off)
$mod=&$mod->$key; // overwrite $mod by reference while traversing
}
unset($mod->$last); // unset the last object
var_export($xml); // print modified $xml to screen
遍歷除最后一項之外的鍵數組,最后執行取消設置。 但是通過引用分配給 $temp !!
$temp = &$xml;
$keys_arr = ['a', 'b', 'c'];
for($i,$size=count($keys_arr); $i<$size-1; $i++){
$temp = &$temp->$keys_arr[$i];
}
unset($temp->$keys_arr[$i]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.