Run the loop in advance and populate an array, which in turn you include in the $result
afterward.
<?php
// Create an empty array
$comlistall = array();
foreach ( $comments as $comment ){
$comlistall[] = $comment; // <= Populate the array with the comments in the loop
};
$rtitlez = get_the_title();
$rimgz = get_the_post_thumbnail_url(get_the_ID(), 'full');
$rvaluez = get_post_meta($post->ID, 'comments_rating_value', true);
$rcountz = get_post_meta($post->ID, 'comments_rating_count', true);
$result = [
"@context" => "https://schema.org/",
"@type" => "Organization",
"name" => $rtitlez,
"image" => $rimgz,
"aggregateRating" => [
"@type" => "AggregateRating",
"ratingValue" => $rvaluez,
"bestRating" => "5",
"worstRating" => "1",
"ratingCount" => $rcountz
],
"comlistall" => $comlistall, // insert the comment array in your $results array
];
?>
<script type="application/ld+json"><?php echo json_encode($result); ?></script>
Update
If you only want certain attributes from the comments, simply create your own array with the attributes you want. In this example $comment
is an array with the attributes. Modify to your needs.
// ...
foreach ( $comments as $comment ){
$c = [
"@type" => "Review",
"headline" => $comment["headline"],
"reviewbody" => $comment["reviewbody"],
"datePublished" => $comment["datePublished"],
"itemReviewed" => [
"@type" => "Organization",
"name" => $comment["name"],
],
"author " => [
"@type" => "Person",
"name" => $comment["authorname"],
],
];
$comlistall[] = $c;
};
// ...