亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 foreach 循環中為 JSON 使用 array_key_exists

如何在 foreach 循環中為 JSON 使用 array_key_exists

PHP
Helenr 2022-07-09 09:50:34
我有一些代碼在我的項目中迭代 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,或者我應該完全做其他事情?謝謝
查看完整描述

2 回答

?
長風秋雁

TA貢獻1757條經驗 獲得超7個贊

您可以檢查是否comment未在此處設置:


if ($counter > 3 || !isset($review['comment']))  {

    //do nothing

} else {

    $counter++;

    //HTML

}

但是,我可能會翻轉if邏輯,您不需要else:


if ($counter <= 3 && isset($review['comment']))  {

    $counter++;

    //HTML

}

如果您有大型數組,如果您顯示的數組超過 3 個(或某個數字),您可能希望跳出循環:


if ($counter > 3)

    break;

} elseif (isset($review['comment']))  {

    $counter++;

    //HTML

}

如果你愿意,你可以用!array_key_existsandarray_key_exists代替s。isset


查看完整回答
反對 回復 2022-07-09
?
皈依舞

TA貢獻1851條經驗 獲得超3個贊

我認為這是簡單的方法


if(isset($test[$key_check])){

    echo  $value = $test[$key_check];

}

或檢查數組是否存在:


if (array_key_exists($key_check, $test)) {

    return $test[$key_check];

}


查看完整回答
反對 回復 2022-07-09
  • 2 回答
  • 0 關注
  • 128 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號