-1

I need json response in different array, but below code not give all the result.

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);
alexander.polomodov
  • 5,396
  • 14
  • 39
  • 46
  • 1
    You are overwriting `$data` every loop iteration – Roland Starke Mar 12 '16 at 10:39
  • If you pass `TRUE` as the second argument to [`json_decode()`]() it returns an array that it's easier to handle than a `stdClass` object. Something like `$json_res=json_decode($res, TRUE); $data['time']=$json_res['rows'][0]'elements'][0]['duration']['text'];` – axiac Mar 12 '16 at 11:20

1 Answers1

0

You need to save your items into some array, e.g $dataArray at the end of each iteration and after cycle use this array to create 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);
alexander.polomodov
  • 5,396
  • 14
  • 39
  • 46