如何组合两个PHP“foreach”循环
我正在尝试使用一些 xpath 解析一个非常简单的 HTML 文档。共有 20 张图片和 20 个链接。我唯一的目标是将每个链接应用于其相应的图像。
我当前的代码如下返回每个图像多次。例如,当前显示了 20 次的第一张图像在每个实例中都应用了不同的链接。因此,图像 #1 的实例 #1 应用了链接 #1,图像 #1 的实例 #2 应用了链接 #2,依此类推。
我想要做的是将每个图像包含一次并对其应用相应的链接,因此我有 20 个图像,并对其应用了相应的链接。我很确定我需要结合我的两个 foreach 函数,但我不太确定如何做到这一点。任何帮助都会很棒,谢谢大家。
foreach ( $images = $xpath->query("//div[@class='image']//a//img") as $image )
{
foreach ( $links = $xpath->query("//div[@class='image']//a") as $link )
echo "<a href='" . $link->getAttribute( 'href' ) . "'><img src='" . $image->getAttribute( 'src' ) . "'</a>", "\n";
}
I'm trying to parse a really simple HTML document with some xpath. There are a total of 20 images and 20 links. My only goal is to get each link applied to it's corresponding image.
My current code below is returning each image a bunch of times. So for example, that first image, which is currently showing 20 times, has a different link applied to it with each instance. So instance #1 of image #1, has link #1 applied to it, instance #2 of image #1 has link #2 applied to it, and so on.
What I want to do is include each image once and apply the corresponding link to it, so I have 20 images, with their corresponding links applied to them. I'm pretty sure I need to combine my two foreach functions, but I'm not quite sure how to do that. Any help would be awesome, thanks guys.
foreach ( $images = $xpath->query("//div[@class='image']//a//img") as $image )
{
foreach ( $links = $xpath->query("//div[@class='image']//a") as $link )
echo "<a href='" . $link->getAttribute( 'href' ) . "'><img src='" . $image->getAttribute( 'src' ) . "'</a>", "\n";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
扩展 Ignacio 的想法...
首先,查询包含图像的所有锚元素
然后,使用锚作为图像搜索的上下文
更新
对我来说,这对于 XSL 转换来说似乎是更合适的工作
Expanding on Ignacio's idea...
First, query for all anchor elements containing images
Then, use the anchor as the context for the image search
Update
To me, this seems a much more appropriate job for an XSL transformation
好的,如果我理解正确的话,在执行 xpath 查询后,您最终会得到两个数组,每个数组具有相同数量的元素,并且它们都匹配,这意味着 $images[x] 需要 $links[x] 为任何x 的值。
像这样的事情可能会起作用:
OK so if I understand correctly, after doing the xpath queries you'd end up with two arrays, each with the same number of elements, and they're all matched, meaning $images[x] needs $links[x] for any value of x.
Something like this may work: