php - 如何运行 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
}
解决方案
以下是如何执行此操作的示例:
<?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' ] ) );
推荐阅读
- sql-server - T-SQL 无法查询具有多个嵌套命名空间且没有唯一 ID 的 XML
- android - ChromeCast 是否支持在 WebVTT 字幕流中格式化字幕文本?
- python - 通过按不同列的不同值计算出现次数来创建新 df 的函数
- java - 哪里可以下载一整套maven仓库jar文件?
- laravel-5 - 我可以在一个地方(一个模型)使用 eloquent ORM 和 Query Builder 吗?
- python-3.x - 使用字典代替字典列表来降低程序复杂度
- python-2.7 - 无法在 linux alpine 上运行 picovoice
- javascript - 如何为切换按钮设置 Firebase 规则
- batch-file - 我如何制作它以便它接受变量输入并在完成后创建一个文本文件
- python - 如何从文件夹中分离两个不同命名的文本文件。是否有任何分类器直接基于赋予文件的标题