PHP中的递归问题
我需要从给定的 array() 创建一个有效的 xml;
我的方法看起来像这样,
protected function array2Xml($array)
{
$xml = "";
if(is_array($array))
{
foreach($array as $key=>$value)
{
$xml .= "<$key>";
if(is_array($value))
{
$xml .= $this->array2Xml($value);
}
$xml .= "</$key>";
}
return $xml;
}
else
{
throw new Exception("in valid");
}
}
protected function createValidXMLfromArray($array,$node)
{
$xml = '<?xml version="1.0" encoding="ISO-8859-1"?>';
$xmlArray = $this->array2Xml($array);
$xml .= "<$node>$xmlArray</$node>";
return $xml;
}
如果我执行上面的代码,我只会得到带有空值的键;
就像
<node>
<name></name>
</node>
我需要的是,如果我通过这个 array("name"=>"test","value"=>array("test1"=>33,"test2"=>40));
它返回这个
<node>
<name>test</name>
<value>
<test1>33</test1>
<test2>40</test2>
</value>
</node>
错误在哪里,我在上面的递归中做错了什么?
I need to create a valid xml from a given array();
My Method looks like this,
protected function array2Xml($array)
{
$xml = "";
if(is_array($array))
{
foreach($array as $key=>$value)
{
$xml .= "<$key>";
if(is_array($value))
{
$xml .= $this->array2Xml($value);
}
$xml .= "</$key>";
}
return $xml;
}
else
{
throw new Exception("in valid");
}
}
protected function createValidXMLfromArray($array,$node)
{
$xml = '<?xml version="1.0" encoding="ISO-8859-1"?>';
$xmlArray = $this->array2Xml($array);
$xml .= "<$node>$xmlArray</$node>";
return $xml;
}
if i execute the above i just get keys with empty values;
like
<node>
<name></name>
</node>
What i need is if i pass this array("name"=>"test","value"=>array("test1"=>33,"test2"=>40));
that it return this
<node>
<name>test</name>
<value>
<test1>33</test1>
<test2>40</test2>
</value>
</node>
Where is the error what did i wrong in the above recursion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你忘了“其他”:
You forgot the "else":
您从未将这些值放入代码中;你的递归没问题,你只是错过了提供数据的最重要的步骤。试穿一下尺码:
You never placed the values into the code; your recursion is OK, you just missed the all-important step of supplying the data. Try this on for size:
或许
?
Maybe
?
你错过了一件事,在检查 $value 是否为数组后,你需要添加 else
否则 $xml .= $value;
如果你明白我的意思
you are missing one thing, after your check if $value is array you need to add else
else $xml .= $value;
if you know what I mean