【发布时间】:2023-03-13 11:30:01
【问题描述】:
我有一些代码在我的项目中迭代 JSON 以在滑块中显示评论。此代码有效,但是我只想显示存在数组键“comment”的评论。我觉得解决方案必须使用array_key_exists,但我无法正确获取代码(我还是个 PHP 新手)。我已经尝试在整个 SO 上进行搜索,但没有取得多大成功。这是我正在使用的一些 JSON 的示例; REVIEW ID 1 是我要显示的评论,而 REVIEW ID 2 是我要跳过的评论:
{
"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/"
},
这是运行评论的代码:
$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;?>
我怎样才能在上面正确地实现 array_key_exists,或者我应该完全做其他事情?谢谢
【问题讨论】:
标签: php