简体   繁体   English

使用 PHP 格式化 API JSON 响应

[英]Formatting API JSON response using PHP

I have an api and i want to parse data from it using php我有一个 api,我想使用 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>";
}

You can easily list all medicine names with their id like this way by looping $array['data'] array.通过循环$array['data']数组,您可以像这样轻松地列出所有带有 id 的药物名称。 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工作演示: https : //3v4l.org/tBtaW

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM