如何获取元素值为1的所有元素名称到数组中?
问题描述:
这里是我的XML数据的〔实施例:如何获取元素值为1的所有元素名称到数组中?
<features>
<bedrooms>1</bedrooms>
<bathrooms>1</bathrooms>
<ensuite></ensuite>
</features>
我访问这个像这样:
$data->features;
我基本上要使它所以它遍历,如果它有一个1它将它添加到数组中。
然后,我可以破灭,并得到下面的结果:
bedrooms, bathrooms
套房,因为它没有一个不存在以上。
我该如何循环并将其添加到数组?
我已经试过:
foreach($data->features as $key => $val){
$features[] = $val;
}
,但不起作用。
谢谢。
答
使用的SimpleXML:
$lib = simplexml_load_file("test.xml");
$children = $lib->children()[0];
$features = array();
foreach($children as $node){
$features[] = $node->title;
}
print_r($features);
答
foreach($data->features as $child){
foreach ($child as $k => $v){
if ($v == 1){
$features[] = $k;
}
}
}
这似乎是工作,但它是一个很好的方式?
看起来像遍历XML结构就好。这是你将不得不做的,看看哪些设置为1,哪些不是。 – Husman 2013-02-27 10:08:24
这样做绝对没问题。您还可以使用[XPath](http://schlitt.info/opensource/blog/0704_xpath.html)查询包含nodeValue的节点,例如,做$ foreach($ features-> xpath('* [text()= 1]')为$ feature){$ elementNames [] = $ feature-> getName(); }' – Gordon 2013-02-27 10:40:39