如何从php中的动态变量创建关联数组?

时间:2011-03-10 15:11:53

标签: php arrays dynamic associative

我有这段代码:

$people=array();
$i=0;
foreach ($xml->xpath('//person') as $character) {
if ($character->status!="Active"){

  $people[$i]['fullname']=(string)$character->fullname;
  $people[$i]['status']=(string)$character->status;
  $i++;

    }
}

它根据$ i的值创建一个带数字键的数组。但是,我实际上并不想这样,我希望“fullname”字符串成为键,但我无法弄清楚如何动态分配键。我正在尝试这样的事情:

$people[(string)$character->fullname]=>(string)$character->status;

但这只会引发错误。我无法弄清楚如何根据变量创建密钥。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:7)

再次尝试此操作,但使用=,而不是=>

$people[ (string) $character->fullname ] = (string) $character->status;

答案 1 :(得分:1)

您只在数组定义中使用=>。否则只需使用沼泽标准赋值:

$people[$character->fullname] = $character->status;

你不需要演员,因为你已经有了弦乐。即使你没有,你也可以简单地依靠动态类型在输出时根据需要进行转换。

答案 2 :(得分:0)

$people[$character->fullname] = (string)$character->status;