具有可变键名称的PHP关联数组

时间:2014-01-04 01:27:50

标签: php arrays

我正在尝试创建一个关联数组,其中键是电子邮件地址,值是密码。它从XML数据库读取以获取信息。这是我的代码:

$data = simplexml_load_file("Treasury.xml");
//Add in all passwords
for ($i = 0; $i < count($data->Member); $i++) {
    $key = $data->Member[$i]->Email + '';
    $USERS[$key] = $data->Member[$i]->Pin;
}

问题出现在for循环中。它获得了成员的正确计数(我打印出来)但是键总是被标记为数字0,导致只有最后一个引脚存储在长度为1的数组中。在语法上是否有我正在做的事情错?

提前致谢。

编辑:我在XML文档中做了第一个用户的var_dump。这是(对不起有多久):

object(SimpleXMLElement)#4 (5) { ["Name"]=> string(19) "Mackenzie Daugherty" ["PC"]=> object(SimpleXMLElement)#2 (0) { } ["Email"]=> string(16) "dau53688@obu.edu" ["Pin"]=> string(4) "0000" ["Payments"]=> object(SimpleXMLElement)#3 (1) { ["Payment"]=> array(2) { [0]=> object(SimpleXMLElement)#5 (7) { ["Type"]=> string(4) "Dues" ["Description"]=> string(18) "Dues for Fall 2013" ["DateIssued"]=> string(7) "8/26/13" ["DateEnd"]=> string(6) "9/9/13" ["Owed"]=> string(2) "55" ["Paid"]=> string(2) "55" ["Plan"]=> object(SimpleXMLElement)#7 (5) { ["InPlan"]=> string(1) "0" ["PlanDescription"]=> object(SimpleXMLElement)#8 (0) { } ["Intervals"]=> string(1) "0" ["Completed"]=> string(1) "0" ["PerInterval"]=> string(1) "0" } } [1]=> object(SimpleXMLElement)#6 (7) { ["Type"]=> string(19) "Tiger Tunes Tickets" ["Description"]=> string(18) "Two Saturday Night" ["DateIssued"]=> string(7) "8/26/13" ["DateEnd"]=> string(7) "8/26/13" ["Owed"]=> string(2) "30" ["Paid"]=> string(2) "30" ["Plan"]=> object(SimpleXMLElement)#7 (5) { ["InPlan"]=> string(1) "0" ["PlanDescription"]=> object(SimpleXMLElement)#8 (0) { } ["Intervals"]=> string(1) "0" ["Completed"]=> string(1) "0" ["PerInterval"]=> string(1) "0" } } } } }

1 个答案:

答案 0 :(得分:3)

正如the documentation that I'm sure you've been studying carefully中明确指出的那样, PHP连接运算符为.,而不是+

您的代码需要两个操作数,并尝试对它们执行算术加法。由于它们不是[有意义的]数字,you end up with 0

(如果不知道您未提供的操作数的精确值,我无法进行更详细的评估。)

您的代码should read

$key = $data->Member[$i]->Email . '';
//                              ^
//  (is the concatenation necessary at all?
//   isn't Email already a string?)

在其他地方进行相同的更正。