我在使用 PHP 数组时遇到了一些问题,据我所知,它应该可以工作。我正在使用 simpleXML 并循环一个 simpleXML 输出。然后,我尝试从相关的 XML 节点中删除“id”属性,将其指定为数组中新项目的键,并将值指定为国家/地区名称。这是我的 simpleXML 输出示例($cxml
在下面的代码中):
SimpleXMLElement Object (
[country] => Array (
[0] => SimpleXMLElement Object (
[@attributes] => Array ( [id] => AD )
[name] => ANDORRA
[ssc] => EUR
)
[1] => SimpleXMLElement Object (
[@attributes] => Array ( [id] => AE )
[name] => UNITED ARAB EMIRATES
[ssc] => EUR
)
[2] => SimpleXMLElement Object (
[@attributes] => Array ( [id] => AF )
[name] => AFGHANISTAN
[ssc] => ASI
) ...
)
等等。这是我的代码:
function generateCountryList() {
global $server_path;
// the following line generates - correctly - the object I gave above
$cxml = simplexml_load_file($server_path . 'countries/');
$c = array();
foreach ($cxml->country as $cntry => $rec) {
$rid = $rec['id'];
$rname = ucwords(strtolower($rec->name));
//the following echo statements are for debugging only
echo $rid; //returns the country ID; for example, AD on the 0th element in the object
echo $rname; //returns the country name; for example, Andorra on the 0th element in the object
$c[$rid] = $rname; //the goal here is to have an array of the form
//['AD'=>'Andorra','AE'=>'United Arab Emirates',...]
}
return $c;
}
如果我返回$c
并将其分配给一个变量,那么print_r
该变量,我得到一个空数组。如果我print_r($c);
在这个函数中运行,我会得到同样的结果。
我很感激有人可以提供任何帮助,说明为什么我无法构建这个阵列!