【问题标题】:PHP - Json_encode how to add variable to database selection and passing to Json?PHP - Json_encode 如何将变量添加到数据库选择并传递给 Json?
【发布时间】:2016-07-31 09:10:50
【问题描述】:

我需要从 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"}]}

【问题讨论】:

    标签: php mysql json


    【解决方案1】:

    $rowm 是一个数组,因此通过. 使用字符串连接将不起作用!请试试这个:

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

    希望对你有帮助。

    【讨论】:

    【解决方案2】:
    $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();
    

    【讨论】:

      【解决方案3】:
      $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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-15
        • 2018-02-16
        • 2015-08-24
        • 2019-03-11
        • 1970-01-01
        • 2012-10-31
        • 2012-08-03
        • 1970-01-01
        相关资源
        最近更新 更多