Reputation: 135
I have an api and i want to parse data from it using php
That's the response
{
"success": true,
"data": [
{
"medicineId": 12,
"medicineName": "Abacavir"
},
{
"medicineId": 10,
"medicineName": "Alclometasone"
},
{
"medicineId": 15,
"medicineName": " Alectinib"
},
{
],
"message": "Successfully retrieved"
}
I want to list all medicine names
i tried this but it doesn't get the name just the success response
$age = file_get_contents('link');
$array = json_decode($age, true);
foreach($array as $key=>$value)
{
echo $key . "=>" . $value . "<br>";
}
Upvotes: 2
Views: 1329
Reputation: 38502
You can easily list all medicine names with their id like this way by looping $array['data']
array. Let's do this way-
<?php
$age = '{"success":true,"data":[{"medicineId":12,"medicineName":"Abacavir"},{"medicineId":10,"medicineName":"Alclometasone"},{"medicineId":15,"medicineName":" Alectinib"}],"message":"Successfully retrieved"}';
$array = json_decode($age, true);
$medicine_names = [];
foreach($array['data'] as $key=>$value)
{
$medicine_names[$value['medicineId']] = $value['medicineName'];
}
print_r($medicine_names);
echo implode(' ', $medicine_names);
?>
Output:
Array (
[12] => Abacavir
[10] => Alclometasone
[15] => Alectinib
)
WORKING DEMO: https://3v4l.org/tBtaW
Upvotes: 3