我有一个xml文件,其结构如下:
$xmlString = '
<plist>
<categories>
<category>
<id>1</id>
<parent>0</parent>
<description><![CDATA[Test 1]]></description>
</category>
<category>
<id>2</id>
<parent>1</parent>
<description><![CDATA[Test 1.1]]></description>
</category>
<category>
<id>3</id>
<parent>1</parent>
<description><![CDATA[Test 1.2]]></description>
</category>
</categories>
</plist>';现在我尝试这样构建一个数组:
$xmlData = new SimpleXMLElement($xmlString);
$results = [];
foreach($xmlData->categories->category as $key => $category){
$results[$key]['id'] = isset($category->id) ? (string)$category->id : false;
$results[$key]['parentId'] = isset($category->parent) ? (string)$category->parent : false;
$results[$key]['name'] = isset($category->description) ? (string)$category->description : false;
}
echo '<pre>'.print_r($results,true).'</pre>';但结果只是最后一个条目:
Array
(
[category] => Array
(
[id] => 3
[parentId] => 1
[name] => Test 1.2
)
)SimpleXMLElement对象如下所示:
SimpleXMLElement Object
(
[categories] => SimpleXMLElement Object
(
[category] => Array
(
[0] => SimpleXMLElement Object
(
[id] => 1
[parent] => 0
[description] => SimpleXMLElement Object
(
)
)
[1] => SimpleXMLElement Object
(
[id] => 2
[parent] => 1
[description] => SimpleXMLElement Object
(
)
)
[2] => SimpleXMLElement Object
(
[id] => 3
[parent] => 1
[description] => SimpleXMLElement Object
(
)
)
)
)
)所以类别是一个数组,我不明白为什么foreach循环不能工作。关键字应该是1,2,3还是不是?
发布于 2017-04-05 18:58:49
用这个替换你的循环。$key总是一个相同的密钥。所以它每次都会被覆盖
$counter=0;
foreach($xmlData->categories->category as $category){
$results[$counter]['id'] = isset($category->id) ? (string)$category->id : false;
$results[$counter]['parentId'] = isset($category->parent) ? (string)$category->parent : false;
$results[$counter]['name'] = isset($category->description) ? (string)$category->description : false;
$counter++;
}发布于 2017-04-05 19:03:45
好的,这是一个没有计数器但有简单[]的答案
foreach($xmlData->categories->category as $category){
$results[] = array(
'id' => isset($category->id) ? (string)$category->id : false,
'parentId' => isset($category->parent) ? (string)$category->parent : false,
'name' => isset($category->description) ? (string)$category->description : false,
);
}发布于 2017-04-05 19:02:55
像这样使用
$xmlData = new SimpleXMLElement($xmlString);
$results = [];
$ii = 0;
foreach($xmlData->categories->category as $category){
$results[$ii]['id'] = isset($category->id) ? (string)$category->id : false;
$results[$ii]['parentId'] = isset($category->parent) ? (string)$category->parent : false;
$results[$ii]['name'] = isset($category->description) ? (string)$category->description : false;
$ii++;
}
echo '<pre>'.print_r($results,true).'</pre>';https://stackoverflow.com/questions/43229159
复制相似问题