我正在使用spaceXdata API来学习有关使用PHP(https://api.spacexdata.com/v5/launches)的API的更多信息

但我想做一个随机按钮(获取随机启动数据)

我使用以下代码来获取API中的数据项的数量:

$api_url = 'https://api.spacexdata.com/v5/launches/';
$json_data = file_get_contents($api_url);
$data = json_decode($json_data, true);

foreach($data as $x => $amount){
    $x = $x + 1;
}

但发布的ID不是1、2、3等,而是62a9f86420413d2695d88719等.

如何从API获得随机启动? 例如.我有205次emits ,但我只想要第25次.而无需亲自将所有数据放入数组中

我真的被困在这里了

我希望有人能告诉我如何获得API的第x项

推荐答案

<?php
$api_url = 'https://api.spacexdata.com/v5/launches/';
$json_data = file_get_contents($api_url);
$data = json_decode($json_data, true);

// Get the total number of launches in the API
$num_launches = count($data);

// Generate a random number within the range of the number of launches
$random_launch_num = rand(0, $num_launches - 1);

// Use the random number to access the corresponding launch in the API's data
$random_launch = $data[$random_launch_num];

此代码将在API可用启动次数范围内生成一个随机数,然后使用该数字访问API数据中相应的启动.这将使您可以使用PHP从SpaceX API随机启动.

Php相关问答推荐

PHP-转义字符串内的双反斜杠

MariaDB 11.3.2+PHP:服务器向客户端发送未知的字符集(0).请向开发人员报告

在没有谷歌云客户端PHP库的情况下将图像上传到PHP中的Google存储API?

Laravel Nova不使用数组键作为筛选器中的选项值

只收取WooCommerce中最高的运费

如果为布尔值,则 for each 循环重新启动

Shopware 6插件:由于删除了配置密钥,更新后配置值不正确

Filament v3:具有 hasMany 和 BelongsTo 的关系管理器

奇怪的 preg_match_all() 行为

标签打印机的 CSS

如何在 Phpunit 的静态提供程序中创建测试双打?

使用动态地址和动态文件创建zip文件并获取zip文件链接

Woocommerce的数量和价格条件

在 Botiga 主题模板中添加复选框到政策行.Woocommerce

如何更改或管理Carbon时区,使其不会来回移动时钟

如何为多个表的id列设置不同的值

用于多态服务的 Symfony setter 注入

使用 PHP ImageMagick 库将 pdf 文件的前 n 页转换为单个 png 图像文件

从 d-m-Y 日期格式 laravel 计算月份 = 01 的列的总和

PHP 从 API 获取随机项目