如何获取两个表值并在json响应中生成

时间:2017-08-09 06:34:05

标签: php php-5.6

这里我想从MySQL算起来,我是基于行程ID的两个表我想算数,怎么能这样做?。

这里,旅行是常见的,表和旅行ID 1有三个计数,旅行ID 2有两个计数。

  

trip_details(表名)

 tripId        cabNo 

  1          BMW4455

  2          Audi005
  

trip_member(表名)

id    tripId    empId

1     1       100
2     1       101
3     1       102
4     2       105
5     2       106
  

预期结果

{
"status": "success",
"data": [
    {
        "tripId": "1",
        "cabNo": "BMW4455",
        "empcount": "3"
        "employees": [
            {
                "empId": "100",
            },
            {
                "empId": "101",
            },
            {
                "empId": "102",
            }
        ]
    },
    {
        "tripId": "2",
        "cabNo": "Ad2K2001",
        "count": "2"
        "employees": [
            {
                "empId": "100",
            },
            {
                "empId": "101",
            },
            {
                "empId": "102",
            }
        ]
    }
]
}
  

我试过,但我没有得到我的确切答案我的代码

     $sql = "SELECT * FROM trip_details a INNER JOIN trip_member b ON a.tripId=b.tripId GROUP BY a.tripId";
  $mysql = mysql_query($sql);
  $count =mysql_num_rows($mysql);
  if($count > 0){
  while ($row = mysql_fetch_assoc($mysql)) {
    $data[] = $row;
  }
  $arrayName = array('status' => 'success', 'count' => $count, 'data' =>$data );
  echo json_encode($arrayName);
 }else{
$arrayName = array('status' => 'error', 'data' =>'Data not found' );
  echo json_encode($arrayName);
 }
  

我正在获得输出

{
"status": "success",
"count": 2,
"data": [
    {
        "tripId": "1",
        "cabNo": "BMW4455",
        "driverId": "DRE001",
        "routeId": "1",
        "tripDate": "",
        "startTime": "",
        "endTime": "",
        "shiftId": "1",
        "tripStatus": "0",
        "id": "1",
        "empId": "100",
        "callStartTime": "",
        "callEndTime": "",
        "cabReachingTime": "",
        "pickupTime": "",
        "dropTime": "",
        "dropStatus": "",
        "otp": "",
        "pickupotpStatus": "",
        "empPresentStatus": ""
    },
    {
        "tripId": "2",
        "cabNo": "Audi005",
        "driverId": "DRV101",
        "routeId": "2",
        "tripDate": "",
        "startTime": "",
        "endTime": "",
        "shiftId": "1",
        "tripStatus": "0",
        "id": "4",
        "empId": "105",
        "callStartTime": "",
        "callEndTime": "",
        "cabReachingTime": "",
        "pickupTime": "",
        "dropTime": "",
        "dropStatus": "",
        "otp": "",
        "pickupotpStatus": "",
        "empPresentStatus": ""
    }
]
}

1 个答案:

答案 0 :(得分:0)

由于您只需要计数,因此您应将查询更改为:

SELECT count(*) as count, tm.tripId from trip_details td
JOIN trip_member tm on tm. tripId = td.tripId
GROUP by tm.tripId