PHP - Json_encode如何将变量添加到数据库选择并传递给Json?

时间:2016-07-30 15:45:04

标签: php mysql json

我需要从MySQL数据库中获取数据,在它附近添加一个变量,然后以JSON格式显示它。

输出应如下所示:

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

表格不包含距离,应计算距离并在代码中手动添加。

代码:

$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);
}

如何添加到输出的距离?

我试过了:

$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);
}

目前,脚本输出:

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

我希望它看起来像这样:

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

3 个答案:

答案 0 :(得分:1)

$rowm是一个数组,因此通过.使用字符串连接将无法正常工作!请试试这个:

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

我希望这会对你有所帮助。

答案 1 :(得分:0)

$result = mysqli_query($con,"SELECT * FROM `items`");

while($rowm = mysqli_fetch_assoc($result))
{
    $all['items'][] = array_values($rowm);
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode($all);
die();

答案 2 :(得分:0)

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

while($rowm = mysqli_fetch_array($result))
{
    $distance={calc of distance};
    $all[]=array(
            "cinemaname"=>$rowm['name']
        ,   "logo"=>$rowm['logo']
        ,   "distance"=>$distance); 
}
$alldata = array('items'=>$all);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($alldata);