J. Doe J. Doe - 4 months ago 29
MySQL Question

PHP - Json_encode how to add variable to database selection and passing to Json?

I need to get the data from Mysql database, add a variable near it and then show it in json format.

The output should look like this:

{"items":[{"cinemaname":"Cinema name","logo":"upload/cinemaname.png","distance":"103"},{"cinemaname":"Cinema name 2","logo":"upload/cinemaname2.png","distance":"23"}]}

The table does not consist of the distance, the distance should be calculated and added manually in the code.

The code:

$result = mysqli_query($con,"some query here");

while($rowm = mysqli_fetch_array($result))
{



$all[]= $rowm;

}

$alldata = array('items'=>$all);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($alldata);
}


How can I add the distance to the output?

I tried in this way:

$result = mysqli_query($con,"some query here");

while($rowm = mysqli_fetch_array($result))
{
//here is calculation of a distance = $distance

$all[]= $rowm.'distance=>'.$distance;

}

$alldata = array('items'=>$all);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($alldata);
}


With current script it shows in this way:

{"items":[{"cinemaname":"Cinema name","logo":"upload/cinemaname.png"},{"cinemaname":"Cinema name 2","logo":"upload/cinemaname2.png"}]}

Need to show in this:

{"items":[{"cinemaname":"Cinema name","logo":"upload/cinemaname.png","distance":"103"},{"cinemaname":"Cinema name 2","logo":"upload/cinemaname2.png","distance":"23"}]}

Answer

$rowm is an array so using strings concatenation via . will not work ! please try this:

$rowm['distance'] = $distance;
$all[] = $rowm;

I hope this will help you.

Comments