从简单的 xml 对象获取多维数组时出现问题
作为新手,我需要您的帮助来从 simplexml 对象获取多维数组。 假设我的数组是这样的: 只是为了获得想法:
这里 $data 是一个 simplexml 对象,包含以下 xml:
<users>
<user>
<id></id>
<nm></nm>
<gender>
<male></male>
<female></female>
</gender>
</user>
</users>
这里我完美地获取了每个用户的数组,但是在该数组中,当涉及到性别时,它什么也没有显示。我也需要性别数组。我正在使用以下代码:
foreach($data->users as $users)
{
$arr1 = array();
foreach($users as $user)
{
foreach($user as $k=>$v)
{
$arr1[$k] = (string) $v;
}
}
$arr2[] = $arr1;
}
有什么建议吗?
As a newbie I need your help in getting multidimensional array from simplexml object.
suppose my array is like:
just for getting idea:
Here $data is a simplexml object contains below xml:
<users>
<user>
<id></id>
<nm></nm>
<gender>
<male></male>
<female></female>
</gender>
</user>
</users>
Here I an perfectly getting array of each user, but in that array when it comes to gender, it shows nothing. i need array of gender too. I am using following code:
foreach($data->users as $users)
{
$arr1 = array();
foreach($users as $user)
{
foreach($user as $k=>$v)
{
$arr1[$k] = (string) $v;
}
}
$arr2[] = $arr1;
}
Any suggestion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您没有正确使用 foreach 迭代器。它应该是这样的:
现在我不知道你想对你的性别做什么,这两个元素都是空的,这是什么意思?
You're not using the foreach iterator correctly. It should be something like this:
Now I have no idea what you're trying to do with your gender thing, both elements are empty, what does that mean?
foreach($user as $k=>$v)
不会迭代user
元素中的所有子元素。它迭代作为$users
子级的所有user
元素。例如:prints
您可能想要更像
which prints 的东西
foreach($user as $k=>$v)
doesn't iterate over all the child elements in youruser
element. It iterates over alluser
elements that are children of$users
. For illustration:prints
You probably want something more like
which prints