如何从php数组获取json输出

oknwwptz  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(307)

这是我用于json输出的php代码:

$sql="SELECT id,name FROM languages ORDER BY id";
    $result=mysqli_query($conn,$sql);

    // Fetch all
    $result = mysqli_fetch_all($result,MYSQLI_ASSOC);

    $out_put = json_encode($result);
    echo $out_put;

这是上述php代码的json输出:

{
    "0": {
        "id": "1",
        "name": "English"
    },
    "1": {
        "id": "2",
        "name": "Kanada"
    },
    "2": {
        "id": "3",
        "name": "Hindi"
    },
    "3": {
        "id": "4",
        "name": "Telugu"
    }
}

但我想要这样的输出:

{
 "Responsecode":200,
 "Message":"Sucess",
 "languagelist": [
   {
     "id": "1",
     "name": "English"
   },
   {
     "id": "2",
     "name": "Kannada"
   },
   {
     "id": "3",
     "name": "Hindi"
   },
   {
     "id": "4",
     "name": "Telugu"
   }
 ]
}

我正在尝试创建api,我是新的。请帮忙。先谢谢你。

dfddblmv

dfddblmv1#

写吧

$out_put = json_encode([
   "Responsecode" => 200,
   "Message" => "Sucess",
   "languagelist" => $result
]);
5kgi1eie

5kgi1eie2#

你可以这样做:

$output['Responsecode'] = 200;
$output['Message'] = "Sucess";
$output['languagelist'] = $result;
$out_put = json_encode($output);

相关问题