猿问

如何在 foreach 循环中为 JSON 使用 array_key_exists

我有一些代码在我的项目中迭代 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 {

         ?>


如何在上面正确实现 array_key_exists,或者我应该完全做其他事情?谢谢


Helenr
浏览 105回答 2
2回答

长风秋雁

您可以检查是否comment未在此处设置:if ($counter > 3 || !isset($review['comment']))&nbsp; {&nbsp; &nbsp; //do nothing} else {&nbsp; &nbsp; $counter++;&nbsp; &nbsp; //HTML}但是,我可能会翻转if逻辑,您不需要else:if ($counter <= 3 && isset($review['comment']))&nbsp; {&nbsp; &nbsp; $counter++;&nbsp; &nbsp; //HTML}如果您有大型数组,如果您显示的数组超过 3 个(或某个数字),您可能希望跳出循环:if ($counter > 3)&nbsp; &nbsp; break;} elseif (isset($review['comment']))&nbsp; {&nbsp; &nbsp; $counter++;&nbsp; &nbsp; //HTML}如果你愿意,你可以用!array_key_existsandarray_key_exists代替s。isset

皈依舞

我认为这是简单的方法if(isset($test[$key_check])){&nbsp; &nbsp; echo&nbsp; $value = $test[$key_check];}或检查数组是否存在:if (array_key_exists($key_check, $test)) {&nbsp; &nbsp; return $test[$key_check];}
随时随地看视频慕课网APP
我要回答