如何将键和值添加到数组? [英] How to add keys and values to an array?

查看:60
本文介绍了如何将键和值添加到数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码来解析以下xml,并将每个人的ID添加为数组的键,并将其名称添加为数组的值.

I am using following code to parse the following xml and add the id of each person as key of the array and their names as the values of the array.

代码正常工作,但数组无效.

The code properly works but the array is not.

   $array = array();
   $category = $xml->xpath('descendant::person');
    foreach ($person as $p) {
    $array[$p['id']] = $p['name'];
    }

 <?xml version="1.0" encoding="utf-8"?>
 <people>
   <person name="Joe" id="134">
   <person name="Jack" id="267">
   </person>
   </person>

   <person name="Ray" id="388">
   <person name="John" id="485">
   <person name="Rayan" id="900">
   </person>
   </person>

   <person name="Alex" id="590">
   </person>
 </people>

该XML无效,但我无法使其有效.但是代码可以正常工作,我只需要向数组分配ID和值即可.

The XML is not valid but I ca not make it valid. However the code is working and I just need to assign the ids and values to the array.

推荐答案

这里有很多小问题……最大的问题是,您不能将simplexml对象节点用作数组中的索引.必须手动将其强制转换为字符串或整数.最好还是稍微调整一下xpath表达式,并且循环不应该放在$ person上,这是一个不存在的变量,而是放在$ category上.尝试以下方法:

Lots of little issues going on here ... the biggest problem, though, is that you can't use a simplexml object node as an index in an array. It has to be manually cast as a string or integer. You'd also be better served tweaking your xpath expression a bit, and your loop shouldn't be on $person, which is a variable that doesn't exist, but instead on $category. Try this as an alternative:

$array = array();
$category = $xml->xpath('//person');
while(list( , $p) = each($category)) {
        $array[(string)$p['id']] = (string)$p['name'];
}
print_r($array);

还请注意,如果您的XML不是有效的XML,那就很重要了……simplexml库将永远无法在无效的XML上正常运行(示例中的XML有不正确的嵌套).

Also note that, if your XML is not valid XML, then it does matter ... simplexml libraries will never function properly on invalid XML (the XML in your example has some improper nesting).

这篇关于如何将键和值添加到数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆