位于https://api.spacexdata.com/v3/launches/past的API端点返回数据。我需要过滤这些数据以在屏幕上显示一个json,该json仅包含API数据条目,其中customers
字段中带有“ DARPA”,而launch_year
字段中带有“ 2017”。 customers
和payloads
流体是任意长度的数组。
响应数据的第一项如下所示。省略了其许多字段。请访问API链接以查看完整响应。
0
flight_number 1
mission_name "FalconSat"
upcoming false
launch_year "2006"
launch_date_unix 1143239400
launch_date_utc "2006-03-24T22:30:00.000Z"
launch_date_local "2006-03-25T10:30:00+12:00"
is_tentative false
tentative_max_precision "hour"
tbd false
launch_window 0
rocket
rocket_id "falcon1"
rocket_name "Falcon 1"
rocket_type "Merlin A"
first_stage {…}
second_stage
block 1
payloads
0
payload_id "FalconSAT-2"
norad_id []
reused false
customers
0 "DARPA"
我该怎么办?
答案 0 :(得分:1)
您在这里:
<?php
$data = json_decode(file_get_contents('https://api.spacexdata.com/v3/launches/past'), true);
foreach($data as $entry) {
if($entry['launch_year'] === '2017') {
if(isset($entry['rocket']['second_stage']['payloads'])) {
foreach($entry['rocket']['second_stage']['payloads'] as $payload) {
foreach($payload['customers'] as $customer) {
if($customer === 'DARPA') print_r($entry);
}
}
}
}
}
您将需要自行添加一些错误处理。 代码有效,但是2017年没有DARPA客户。如果您查看2006,那么它将找到它。
答案 1 :(得分:1)
你在这里
fetch('https://api.spacexdata.com/v3/launches/past')
.then(res => res.json())
.then(response => {
const res = response.filter(
x =>
x.launch_year === '2007' && x.rocket.second_stage.payloads.some(payload => payload.customers.includes('DARPA'))
);
console.log(res);
});