我需要将所有$path
变量放在$html
上。运行代码时,第一个$path
位于$html
,但所有其他$path
推出了$html
。
<?php
$posts = get_posts('cat=4');
foreach ($posts as $post) {
$postId = get_the_ID($post);
$postPrintId = $post->post_name;
$paths = get_field('path', $postId);
if($paths) {
foreach($paths as $path) {
$cordenadas = $path['cordenadas'];
$path = '<path d="'.$cordenadas.'"/>';
}
}
$html = '<g id="'.$postPrintId.'">';
$html .= $path;
$html .= '</g>';
$html .= '';
echo $html;
}
?>
答案 0 :(得分:2)
你每次在foreach循环中覆盖$path
,你需要使用.=
来连接该值,并确保在循环之前清除以避免它加倍下次:
$posts = get_posts('cat=4');
foreach ($posts as $post) {
$postId = get_the_ID($post);
$postPrintId = $post->post_name;
$paths = get_field('path', $postId);
$path = ''; // reset each iteration
if($paths) {
foreach($paths as $path_info) {
$path .= '<path d="' . $path_info['cordenadas'] . '"/>';
// ^---- concatenate, not replace!
}
}
$html = '<g id="'.$postPrintId.'">' . $path . '</g>';
echo $html;
}
正如所指出的,您还使用$path
作为循环变量和包含结果的外部变量。
答案 1 :(得分:1)
上述答案的替代方案。 但产生相同的输出,有些人可能称之为hackish。
因此,请添加以下内容,而不是添加$html .= $path
。
$html .= implode('', $paths);
然后将for循环中的$paths as $path
更改为$paths as &$path
。 (请注意&符号?)
implode函数获取数组中的所有变量,并用字符串分隔它们。在这种情况下,字符串为''
。
&符号告诉PHP使变量成为引用。这允许我们在数组中轻松修改它。