I have some code that iterates over JSON in my project to display reviews in a slider. This code works, however I only want to display reviews where the array key 'comment' exists. I feel like the solution must be using array_key_exists, but I can't get the code correct (I'm still quite a novice with PHP). I've tried searching all over SO without much success. Here's an example of some of the JSON I'm working with; REVIEW ID 1 is review that I want to display, and REVIEW ID 2 is one I want to skip:
{
"reviewId": "{REVIEW ID 1}",
"reviewer": {
"profilePhotoUrl": "{PROFILE PHOTO URL}",
"displayName": "PERSON 1"
},
"starRating": "FIVE",
"comment": "This is a review",
"createTime": "2019-08-30T15:38:59.412Z",
"updateTime": "2019-08-30T15:38:59.412Z",
"reviewReply": {
"comment": "{REVIEW REPLY}",
"updateTime": "2019-08-30T16:05:58.184Z"
},
"name": "accounts/{ACCOUNT NUMBER}/locations/{LOCATION NUMBER}/reviews/"
},
{
"reviewId": "{REVIEW ID 2}",
"reviewer": {
"profilePhotoUrl": "{PROFILE PHOTO URL}",
"displayName": "PERSON 2"
},
"starRating": "FIVE",
"createTime": "2019-02-07T14:59:28.729Z",
"updateTime": "2019-02-07T14:59:28.729Z",
"name": "accounts/{ACCOUNT NUMBER}/locations/{LOCATION NUMBER}/reviews/"
},
And here's the code that runs the reviews:
$jsonreviews = plugin_dir_path( __DIR__ ) . './latest.json';
$reviews2var = file_get_contents($jsonreviews);
$reviews = json_decode($reviews2var, true);
$starpath = plugin_dir_url( __FILE__ ) . './img/fivestars.svg';
$truckpath = plugin_dir_url( __FILE__ ) . './img/chad_love_truck.png';
// Start buffer
ob_start();
?>
<div class="reviews-background">
<div class="swiper-container review-container">
<div class="swiper-wrapper review-wrapper">
<?php
$counter = 1;
foreach ($reviews['reviews'] as $review) :
if ($counter > 3) {
//do nothing
} else {
?>
<div class="swiper-slide review-slide">
<img src="<?php echo $starpath;?>" alt="5 Stars" class="five-stars" />
<?php $counter++;?>
<div class="truncate" data-excerpt>
<div data-excerpt-content>
<p class="slider-review-text">
<?php echo $review['comment'];?></p>
</div>
</div>
<p class="slider-review-auth">
<?php echo $review['reviewer']['displayName'];?>,
</p>
</div>
<?php } ?>
<?php endforeach;?>
How can I properly implement array_key_exists in the above, or should I be doing something else entirely? Thank you