首页 > 解决方案 > 如何运行 do-while 循环,该循环使用 PHP 检查 JSON 中的值?

问题描述

我正在尝试创建一个 do-while 循环,它检查 JSON 中是否仍然存在一个值 - 我的基本想法是在它确实具有特定值时重复调用 API - 最后当 JSON 没有该值,循环将完成运行。

这可能吗?我应该如何检查 JSON 响应中是否存在值?


这是我的回复的样子-(顺便说一句,我每次都会寻找值“偏移”)

{
  "records": [
    {
      "id": "recYxbvL2ScZXt8Pf",
      "fields": {
        "Display": "1) ADWANI AVINASH NIRANJANKUMAR (A2019) (CP) (NN) || recYxbvL2ScZXt8Pf"
      },
      "createdTime": "2021-09-25T13:11:43.000Z"
    },
    {
      "id": "reccXiBSeyMqLAVN0",
      "fields": {
        "Display": "2) AGARWAL NEEDHI SUNIL (A2015) (CP) (NN) || reccXiBSeyMqLAVN0"
      },
      "createdTime": "2021-09-25T13:11:43.000Z"
    },
    {
      "id": "rec7G80Xihuc7cLwu",
      "fields": {
        "Display": "3) AGARWAL UMESH LUXMANLAL (F1990) (CP) (NN) || rec7G80Xihuc7cLwu"
      },
      "createdTime": "2021-09-25T13:11:43.000Z"
    }
    .
    .
    .
  ],
  "offset": "itrwUFrVOdUJauKgs/recOA1j1y2VaRbTcs" //this value
}

标签: phpjsonapiwhile-loop

解决方案


以下是如何执行此操作的示例:

<?php

const DUMMY_JSON_RESPONSES = [
  '{"id":"response 1","offset":"itrwUFrVOdUJauKgs/recOA1j1y2VaRbTcs"}',
  '{"id":"response 2","offset":"itrwUFrVOdUJauKgs/recOA1j1y2VaRbTcs"}',
  '{"id":"response 3","offset":"itrwUFrVOdUJauKgs/recOA1j1y2VaRbTcs"}',
  '{"id":"response 4"}'
];

function dummyApiRequest() {
  static $i = 0;

  if( $i >= count( DUMMY_JSON_RESPONSES ) ) {
    $i = 0;
  }

  return DUMMY_JSON_RESPONSES[ $i++ ];
}

// this is the relevant code part:
do {
  // do API request
  $jsonResponse = dummyApiRequest();
  // decode JSON response into an associative array
  $response = json_decode( $jsonResponse, true );
  // json_decode() will return null on error
  if( $response !== null ) {
    // output dummy id key for demonstration purposes
    var_dump( $response[ 'id' ] );
  }
}
while( $response !== null && isset( $response[ 'offset' ] ) );

推荐阅读