【问题标题】:Need proper json response需要正确的 json 响应
【发布时间】:2016-03-12 10:35:55
【问题描述】:

我需要不同数组中的 json 响应,但下面的代码并没有给出所有结果。

while ($row=mysqli_fetch_assoc($result))
{
    //$data[]=$row;
    $data['id']=$row['id'];
    $data['name']=$row['name'];
    $data['Latitude']=$row['Latitude'];
    $data['Longitude']=$row['Latitude'];

    $lat_user=$row['Latitude'];
    $long_user=$row['Longitude'];
    $res=file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json".
        "?units=imperial&origins=$lat,$long&destinations=$latuser,$longuser");

    $json_res=json_decode($res);
    $data['time']=$json_res->{'rows'}{0}->{'elements'}{0}->{'duration'}->{'text'};

}
echo json_encode($data,true);

【问题讨论】:

  • 每次循环迭代都会覆盖$data
  • 如果您将TRUE 作为第二个参数传递给[json_decode()](),它会返回一个比stdClass 对象更容易处理的数组。类似$json_res=json_decode($res, TRUE); $data['time']=$json_res['rows'][0]'elements'][0]['duration']['text'];

标签: php json cycle


【解决方案1】:

您需要将您的项目保存到某个数组中,例如 $dataArray 在每次迭代结束时使用此数组创建 json

$dataArray = array();
while ($row=mysqli_fetch_assoc($result))
{
    //$data[]=$row;
    $data['id']=$row['id'];
    $data['name']=$row['name'];
    $data['Latitude']=$row['Latitude'];
    $data['Longitude']=$row['Latitude'];

    $lat_user=$row['Latitude'];
    $long_user=$row['Longitude'];
    $res=file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json".
        "?units=imperial&origins=$lat,$long&destinations=$latuser,$longuser");

    $json_res=json_decode($res);
    $data['time']=$json_res->{'rows'}{0}->{'elements'}{0}->{'duration'}->{'text'};
    $dataArray[] = $data;

}
echo json_encode($dataArray,true);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-10
    • 2023-04-02
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多