2在一个json对象

时间:2016-11-18 18:05:25

标签: php mysql json

如何编码两个从我的数据库中的2个不同表中检索数据并在1个json响应中对其进行编码的数组

 Here is my php
    $sql = "select * from schedule;";
 $sql1 = "select * from matches;";  
 $con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name); 

 $result = mysqli_query($con,$sql);
 $result1 = mysqli_query($con,$sql1);


 $response = array();
while($row=mysqli_fetch_array($result))
{
array_push($response, array("n_name"=>$row[1],"start"=>$row[4],"end"=>$row[5],"venue"=>$row[6]));

}

 $data= array();
while($row=mysqli_fetch_array($result1))
{
array_push($data, array("teamone"=>$row[1], "teamtwo"=>$row[2], "s_name"=>$row[10]));
 }



echo json_encode (array("server_response"=>$response, $data));





mysqli_close($con);
?>

我想要的是这样的东西

{
    "server_response": [{
        "n_name": null,
        "start": "2016-11-09 00:00:00",
        "end": "2016-11-16 00:00:00",
        "venue": "aaaaaa",
        "teamone": "aaa",
        "teamtwo": "bbb",
        "s_name": ""
    }]
    }

相反,我得到这样的东西

{
        "server_response": [{
            "n_name": null,
            "start": "2016-11-09 00:00:00",
            "end": "2016-11-16 00:00:00",
            "venue": "aaaaaa"
        }],
        "0": [{
            "teamone": "aaa",
            "teamtwo": "bbb",
            "s_name": ""
        }]
    }

有人能帮助我吗?谢谢!

2 个答案:

答案 0 :(得分:0)

$response = array();
while($row=mysqli_fetch_array($result))
{
    $response['server_response']["n_name"] = $row[1];
    $response['server_response']["start"] = $row[4];
    $response['server_response']["end"] = $row[5];
    $response['server_response']["venue"] = $row[6];
}


while($row=mysqli_fetch_array($result1))
{
    $response['server_response']["teamone"] = $row[1];
    $response['server_response']["teamtwo"] = $row[2];
    $response['server_response']["s_name"] = $row[10];
}

echo json_encode ($response);

答案 1 :(得分:0)

echo json_encode(array(" server_response" => array_merge($ response,$ data)));

echo json_encode(array(" server_response" => $ response + $ data)); //如果你冒两个数组中存在相同密钥的风险