我有一个基本的zend_config_xml实例,它存储一些库存信息,例如哪些产品在补货(replenish_departments)与哪些产品无法重新订购(fashion_departments)。 (fyi我们的产品分为部门,每个部门都有一个独特的alpha代码) 我的xml看起来类似于:
<inventory>
<settings>
<allow_backorders>1</allow_backorders>
<replenish_departments>
<department>M</department>
</replenish_departments>
<fashion_departments>
<department>MF</department>
<department>MS</department>
</fashion_departments>
</settings>
</inventory>
我需要做的是快速判断给定的部门代码是补充还是时尚。我尝试的很简单(或者我认为):
foreach ($inv_settings->replenish_departments as $replenish_deptcode) {
if ($given_deptcode == $replenish_deptcode) return true;
}
但是,我发现当有一个子节点时,你无法迭代它。换句话说,这个代码用于fashion_departments,而不是replenish_departments。
这里的诀窍是什么?
编辑:我发现如果我将$ inv_settings作为foreach中的数组进行类型转换,我可以无错误地进行迭代。现在,这是我正在使用的方法,但我仍然愿意接受更好的解决方案。
答案 0 :(得分:0)
我刚刚写了这个,这对你的情况有用,还是不是你的追求?
$xml = simplexml_load_string("<inventory>
<settings>
<allow_backorders>1</allow_backorders>
<replenish_departments>
<department>M</department>
</replenish_departments>
<fashion_departments>
<department>MF</department>
<department>MS</department>
</fashion_departments>
</settings>
</inventory>
");
foreach ($xml->settings->replenish_departments as $replenish_departments) {
foreach ($replenish_departments as $department)
{
if ($given_deptcode == $department)
return true;
}
}
答案 1 :(得分:0)
您的示例XML配置文件和代码似乎对我来说很好。这是我使用的片段:
$given_deptcode = 'M';
$configuration = new Zend_Config_Xml($config_file);
$inv_settings = $configuration->settings;
foreach ($inv_settings->replenish_departments as $replenish_deptcode) {
if ($replenish_deptcode == $given_deptcode) {
echo $replenish_deptcode . ' needs replenishing!' . PHP_EOL;
}
}
这给出了预期的输出:
M需要补充!
我不确定你是如何得出无法迭代一个项目的结论。
P.S。您可以使用toArray()
方法以数组形式获取配置(或其中的一部分),而不是类型转换为数组。
答案 2 :(得分:0)
只为那些最终来到这里的人(像我一样)。
希望分享一下,现在可以使用最新版本的zend框架来完成。使用1.11.11,但修复已经有一段时间了,请参阅http://framework.zend.com/issues/browse/ZF-2285
$xml = '<?xml version="1.0"?>
<inventory>
<settings>
<allow_backorders>1</allow_backorders>
<replenish_departments>
<department>M</department>
</replenish_departments>
<fashion_departments>
<department>MF</department>
<department>MS</department>
</fashion_departments>
</settings>
</inventory>';
$article = new Zend_Config_Xml($xml);
Zend_Debug::dump($article->toArray());
返回
array(1) {
["settings"] => array(3) {
["allow_backorders"] => string(1) "1"
["replenish_departments"] => array(1) {
["department"] => string(1) "M"
}
["fashion_departments"] => array(1) {
["department"] => array(2) {
[0] => string(2) "MF"
[1] => string(2) "MS"
}
}
}
}
它似乎不允许root多元素。
<inventory>
value1
</inventory>
<inventory>
value2
</inventory>