foreach返回一个var上的所有元素

时间:2014-05-28 20:46:28

标签: php wordpress svg foreach

我需要将所有$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;
    }
?>

2 个答案:

答案 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使变量成为引用。这允许我们在数组中轻松修改它。