Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP get random item from API

I am using the spaceXdata api to learn more about API’s using PHP (https://api.spacexdata.com/v5/launches)

but i wanted to make a random button (get random launch data)

i used this code to get the amount of Data items there are in the api:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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;
}

but the ID’s of the launches are not 1 , 2 , 3 etc. but : 62a9f86420413d2695d88719 etc.

How can i get a random launch from the api?
for example. i have 205 launches, but i only want the 25th launch. without putting all the data in a array myself

Im really stuck in this

I hope someone can tell me how to get the x’th item of an API

>Solution :

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

This code will generate a random number within the range of the number of launches available in the API, and then use this number to access the corresponding launch in the API’s data. This will give you a random launch from the SpaceX API using PHP.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading