JSON格式只获得一列

时间:2018-03-26 14:22:14

标签: php mysql

我是PHP的新手到目前为止我设法以JSON格式从数据库中获取以下输出。我创建了一个返回workorderName的数组结果,但我想在同一个数组中获取workOrderId以便我可以在android字符串请求。

   {
    "result": [
        {
            "$workOrderName": "electrician"
        },
        {
            "$workOrderName": "plumber"
        },
        {
            "$workOrderName": "carpenter"
        }
    ]
}

我的PHP代码是

<?PHP
require_once('connection.php');
$workName = "SELECT work_order_id,workorder_name FROM workorder_category";
$con=mysqli_connect($server_name,$user_name,$password,$db);
$r = mysqli_query($con,$workName);
$result = array();
$resultArr = array('success' => true);
    while($row = mysqli_fetch_array($r)){
        array_push($result,array('$workOrderName'=>$row['workorder_name']));
        }
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>

我希望输出像

{
    "result": [
        {
            "$workOrderId":"1"
            "$workOrderName": "electrician"
        },
        {
            "$workOrderId":"2"
            "$workOrderName": "plumber"
        },
        {
            "$workOrderId":"3"
            "$workOrderName": "carpenter"
        }
    ]
}

2 个答案:

答案 0 :(得分:0)

我很确定你并不意味着在密钥中使用$,但这更容易,并且会从表中为您提供列名(work_order_id,workorder_name)作为键。请务必使用mysqli_fetch_assoc

while($row = mysqli_fetch_assoc($r)){
    $result[] = $row;
}

如果您想更改密钥,则可以在查询中对它们进行别名并使用上述内容:

$workName = "SELECT work_order_id AS workOrderID, workorder_name AS workOrderName FROM workorder_category";

或者你可以构建数组:

$result[] = array('workOrderID'   => $row['work_order_id'],
                  'workOrderName' => $row['workorder_name']);

答案 1 :(得分:-1)

您需要调整代码,以便在数组中添加$workOrderId,如下所示

array_push($result,array(
'$workOrderId' => $row['work_order_id']
'$workOrderName' => $row['workorder_name']
));