【发布时间】:2020-05-27 06:05:04
【问题描述】:
我正在尝试将从 API 获得的多个 JSON 结果合并为一个。
我收到的 JSON 数据如下所示:
{
"total": 100,
"offset": 0,
"articleCollection": [
{
"artikelindeling": {
"artikelgroep": "string",
"artikelgroep_omschrijving": "string",
"kernwoord": "string",
"kernwoord_omschrijving": "string",
"klantgroep": "string",
"klantgroep_omschrijving": "string",
"plaatsbepaling": "string",
"plaatsbepaling_omschrijving": "string",
"unieknummerserie": "string"
},
"artikelinformatie": {
"prijsinformatie": {
"actie": {
"actie_bruto_inkoopprijs": 0,
"actie_consumentenadviesprijs": 0,
"actie_datum_tot_en_met": "2020-02-11T18:19:51.747Z",
"actie_datum_vanaf": "2020-02-11T18:19:51.747Z"
},
"basisprijs_dealer": 0,
"btw": "string",
"btw_omschrijving": "string",
"consumentenadviesprijs": 0
}
},
"dateModified": "2020-02-11T18:19:51.747Z",
"date_modified": "string",
"land": "string",
"taal": "string",
"valuta": "string"
}
]
}
这是我目前使用的代码:
$username = $_POST['username'];
$password = $_POST['password'];
$leverancier = $_POST['leverancier'];
$offset = 0;
$jsonCombined = array();
$data = call_curl($username, $password, $leverancier, $offset); //First call needed to get total amount
$jsonArr = json_decode($data, true);
if ($jsonArr['total'] > 50) { //API limits to 50 results per call, need multiple calls.
$totalCalls = floor($jsonArr['total'] / 50); //Calculate how many calls are needed.
foreach($jsonArr as $record) {
$jsonCombined[] = $record;
}
for ($i = 0; $i < $totalCalls; $i++) {
$offset += 50;
$data = call_curl($username, $password, $leverancier, $offset);
$jsonArr = json_decode($data, true);
foreach($jsonArr as $record) {
$jsonCombined[] = $record;
}
}
}
else {
foreach($jsonArr as $record) {
$jsonCombined[] = $record;
}
}
期望的结果是:
Array ( [total] => 100 [offset] => 0 [articleCollection] => Array ( [0] => Array() [1] => Array() [2] => Array()))
但是,我收到了:
Array ( [0] => 100 [1] => 0 [2] => Array ( [0] => Array() [1] => Array() [2] => Array()))
我将如何进行更改以使密钥保持不变并将其他项目添加到“articleCollection”中?
【问题讨论】: