我在项目中有一些遍历JSON的代码,以在滑块中显示评论。该代码有效,但是我只想在数组键“ comment”存在的地方显示评论。我觉得解决方案必须使用array_key_exists,但是我无法获得正确的代码(我对PHP还是个新手)。我尝试搜索整个SO,但没有取得太大的成功。这是我正在使用的一些JSON的示例;审阅ID 1是我要显示的审阅,而审阅ID 2是我想跳过的审阅: 这是运行评论的代码: 如何在上面正确实现array_key_exists,还是应该完全做其他事情?谢谢 答案 0 :(得分:0) 我认为这是简单的方法 或检查数组是否存在: 答案 1 :(得分:0) 您可以检查此处是否未设置 但是,我可能会翻转 如果数组很大,则显示超过3个(或一些数字)可能要跳出循环: 如果需要,可以用{
"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;?>
2 个答案:
if(isset($test[$key_check])){
echo $value = $test[$key_check];
}
if (array_key_exists($key_check, $test)) {
return $test[$key_check];
}
comment
:if ($counter > 3 || !isset($review['comment'])) {
//do nothing
} else {
$counter++;
//HTML
}
if
逻辑,而您将不需要else
:if ($counter <= 3 && isset($review['comment'])) {
$counter++;
//HTML
}
if ($counter > 3)
break;
} elseif (isset($review['comment'])) {
$counter++;
//HTML
}
!array_key_exists
和array_key_exists
代替isset
。