【问题标题】:How do I run a do-while loop, which is checking a value in a JSON with PHP?如何运行 do-while 循环,该循环使用 PHP 检查 JSON 中的值?
【发布时间】:2021-11-23 04:10:18
【问题描述】:

我正在尝试创建一个 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
}

【问题讨论】:

  • 解析 JSON、检查数据是否存在以及循环是非常基本的 PHP 概念——您能分享一下您目前编写的代码,以及您遇到的具体问题吗?我们不是代码编写服务,但如果您真诚地尝试满足所描述的要求,我们可以为您提供帮助,How to Ask

标签: php json api while-loop


【解决方案1】:

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

<?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' ] ) );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 2016-03-27
    • 2021-07-27
    • 1970-01-01
    • 2021-07-18
    • 2020-02-29
    相关资源
    最近更新 更多