【发布时间】:2014-07-09 02:10:19
【问题描述】:
我正在使用 SimpleXML 来解析来自不同房地产经纪人的房地产清单的 XML 提要。 XML 提要的相关部分如下所示:
<branch name="Trustee Realtors">
<properties>
<property>
<reference>1</reference>
<price>275000</price>
<bedrooms>3</bedrooms>
</property>
<property>
<reference>2</reference>
<price>350000</price>
<bedrooms>4</bedrooms>
</property>
<property>
<reference>3</reference>
<price>128500</price>
<bedrooms>4</bedrooms>
</property>
</properties>
</branch>
<branch name="Quick-E-Realty Inc">
<properties>
<property>
<reference>4</reference>
<price>180995</price>
<bedrooms>3</bedrooms>
</property>
</properties>
</branch>
然后转换成这样的数组:
$xml = file_get_contents($filename);
$xml = simplexml_load_string($xml);
$xml_array = json_decode(json_encode((array) $xml), 1);
$xml_array = array($xml->getName() => $xml_array);
我遇到的问题是,当创建数组时,单个列表的数据在数组中与多个列表的位置不同 - 我不确定如何解释这一点,但如果我 var_dump () 多个项目的数组看起来像这样:
array(3) {
[0]=>
array(3) {
["reference"]=>
string(4) "0001"
["price"]=>
string(6) "275000"
["bedrooms"]=>
int(3)
}
[1]=>
array(3) {
["reference"]=>
string(4) "0002"
["price"]=>
string(6) "350000"
["bedrooms"]=>
int(4)
}
[2]=>
array(3) {
["reference"]=>
string(4) "0003"
["price"]=>
string(6) "128500"
["bedrooms"]=>
int(2)
}
}
如果我 var_dump() 单个列表的数组,它看起来像这样:
array(3) {
["reference"]=>
string(4) "0004"
["price"]=>
string(6) "180995"
["bedrooms"]=>
int(3)
}
但我需要它看起来像这样:
array(1) {
[0]=>
array(3) {
["reference"]=>
string(4) "0004"
["price"]=>
string(6) "180995"
["bedrooms"]=>
int(3)
}
}
这些数组中的每一个都代表来自单个房地产经纪人的房产列表。我不确定这是否只是 SimpleXML 或 json 函数的工作方式,但我需要的是使用相同的格式(包含属性列表的数组是 [0] 键的值)。
提前致谢!
【问题讨论】:
-
我看不出你的
<reference>1</reference>怎么会变成0001这个代码。 json/xml 不会像那样破坏文本节点。 -
我的意思是,每个“属性”都是“属性”的子编号 x,因此没有正确应用此规则 - 对于单个列表,应该可以访问属性列表详细信息,例如这个 $properties['0']['reference'] 但它必须作为 $properties['reference'] 访问。这完全弄乱了我的代码,因为我无法计算有多少列表或正确解析数据。区别在于,对于多个属性,一个列表会被保存,因为有多个子元素,但对于单个属性而言,情况并非如此。
-
在您的预期输出中,
[0]的数组键是否需要为[0]还是需要为与列表相关的特定值? -
数组键 ID 是自动生成的 - 我不需要知道这些 ID 是什么,因为我正在使用 foreach() 但这不适用于单个列表,因为它在做什么而是循环遍历属性 - 如果我使用 count() 来查找数组中的项目数,它们都将返回 3,但对于单个列表,它实际计数的是“参考”、“价格”和“卧室”项目而不是属性的数量。
-
@NoelWhitemore 该死的,我又迟到了。我发布了一个答案,虽然我可能会帮助你解决你所追求的问题。