如何通过在分层键的循环数组(php)中访问它来取消设置对象键

时间:2018-02-22 01:53:40

标签: php arrays xml loops object

我有一个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
                                       ),
                         ),
        )

2 个答案:

答案 0 :(得分:0)

这是一种递归方法(与堆叠相反):

代码:(Demo

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

答案 1 :(得分:-1)

走上除最后一项之外的键数组,最后进行取消设置。但是通过引用分配给$ 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]);