Php foreach循环仅转储一个变量
我有以下代码来查找与preg_match匹配的xml元素Php foreach循环仅转储一个变量,php,xml,Php,Xml,我有以下代码来查找与preg_match匹配的xml元素 foreach($xml->Items->Item->AlternateVersions->AlternateVersion->Binding as $BookBinding) { //loop through the xml data to find the correct ASIN for the kindle edition foreach ($xml->Items->Item-&g
foreach($xml->Items->Item->AlternateVersions->AlternateVersion->Binding as $BookBinding) { //loop through the xml data to find the correct ASIN for the kindle edition
foreach ($xml->Items->Item->AlternateVersions->AlternateVersion->ASIN as $Kindlestring)
{
var_dump ($BookBinding);
if (preg_match('/Kindle Edition/i',$BookBinding))
{
//do stuff
}
}
}
然而,这只是var_转储绑定的第一个循环,为什么呢?我在这里只是猜测,因为我不知道XML的结构,但我猜您在XML的错误部分进行循环。这是我对你应该做什么的猜测:
foreach($xml->Items as $item) {
$bookBinding = $item->Item->AlternateVersions->AlternateVersion->Binding;
$kindleString = $item->Item->AlternateVersions->AlternateVersion->ASIN;
if (preg_match('/Kindle Edition/i',$BookBinding)) {
//do stuff
}
}
此外,它看起来可能有多个交替翻转,因此您可能需要执行如下嵌套循环:
foreach ($xml->Items as $item) {
foreach ($item->Item->AlternateVersions as $version) {
$bookBinding = $version->AlternateVersion->Binding;
$kindleString = $version->AlternateVersion->ASIN;
if (preg_match('/Kindle Edition/i',$BookBinding)) {
//do stuff
}
}
}
很难说没有看到你的数据。首先做一些基本的调试。添加一些echo语句以查看循环失败的地方。确保错误报告处于打开状态。请确保XML对象实际上允许您迭代您试图迭代的元素。@Brad循环甚至没有输入if语句,我做了一个var_转储,它只返回绑定的第一个值,我猜您在XML中只有一个项?不确定为什么要以这种方式循环兄弟元素。当前版本的代码中未引用内部循环,因此您可能应该将其删除以使其更清晰。@user2349095什么是“为隐私而隐藏”?