【问题标题】:Json output changeJson 输出变化
【发布时间】:2019-09-29 20:08:13
【问题描述】:

我的数据库(mysql)

product_name

    ID   product_name   qty
    1     item a      5
    2     item b      4
    3     item c      3

我的php代码

<?php
include("connect.php");
$query="select*from product_name";
$result = mysqli_query($db, $query) or die("Error in Selecting " .mysqli_error($db));
while ($row=mysqli_fetch_assoc($result)){
    $arrey[]=$row;
}
echo json_encode($arrey);
?>

输出是

[{
    "id": "1",
    "productname": "item a",
    "qty": "5"
}, {
    "id": "2",
    "productname": "item b",
    "qty": "4"
}, {
    "id": "3",
    "productname": "item c",
    "qty": "3"
}]

我必须面对像下面这样的数据

{
    "status": "true",
    "message": "Data fetched successfully!",
    "data": [{
            "id": "1",
            "productname": "item a",
            "qty": "5"
        },
        {
            "id": "2",
            "productname": "item b",
            "qty": "4"
        },
        {
            "id": "3",
            "productname": "item c",
            "qty": "3"
        }
    ]
}

怎么做?

【问题讨论】:

  • 如果你只想要一个表中的几个字段,尽量不要使用select * from,而只列出你想要的列select id, productname, qty from。然后,您可以使用mysqli_fetch_all($result, MYSQLI_ASSOC) 一步获取所有行。

标签: php mysql arrays json


【解决方案1】:

您应该将数组添加到标题数组中

    $myArray =  ['status' =>"true", 
                    "message"=> "Data fetched successfully!", 
                    'data' =>$arrey];

.

   <?php
      include("connect.php");
      $query="select*from product_name";
      $result = mysqli_query($db, $query) or die("Error in Selecting " .mysqli_error($db));
      while ($row=mysqli_fetch_assoc($result)){
          $arrey[]=$row;
      }

      $myArray =  ['status' =>"true", 
                    "message"=> "Data fetched successfully!", 
                    'data' =>$arrey];
      echo json_encode($myArray);

  ?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    相关资源
    最近更新 更多