2

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

3
  • you can use echo '<pre>'; var_dump($array); echo '</pre>'; or print_r($array); both will work or you can install chrome extensions like json formatter so that you can save you time in doing that. Commented Jul 6, 2019 at 17:23
  • Have a look here stackoverflow.com/help/someone-answers Commented Jul 7, 2019 at 8:02
  • Thank you, Can you help me with that? stackoverflow.com/questions/56917306/… Commented Jul 7, 2019 at 9:21

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you so much, sorry but i'm not that good in php, what if i want to print only a list of medicine names like Abacavir Alclometasone Alectinib
array_column ;p
instead of print_r?
Yes instead of print_r(); Just implode your array with an space character, see my edit I've updated it.
If the above answe helps then you can mark it as an answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.