I need to put all the $path
variables on $html
. When run the code, the first $path
is on the $html
, but all other $path
's put out the $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;
}
?>
An alternative to the above answer. Produces the same output, though, some might call it hackish.
So, instead of adding $html .= $path
, add the following.
$html .= implode('', $paths);
Then change $paths as $path
in the for loop to $paths as &$path
. (Notice the ampersand?)
The implode function takes all variables in an array, and separates them with a string. In this case, the string is ''
.
The ampersand tells PHP to make the variable a reference. This allows us to modify it easily in the array.
You are overwriting $path
each time in your foreach loop, you need to concatenate that value instead using .=
and make sure it's cleared before the loop to avoid it doubling up next time:
$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;
}
As pointed out, you were also using $path
as your loop variable and an external variable containing results.