php - 将 JSONArray 从 Android 传递到 PHP

标签 php android json arrays

我已经阅读了许多关于 PHP 和 JSONArray 循环的其他问题。我从我的 Android 设备发送一个 JSONArray,其中包含不同学生的值以及他们的类(class)和 studentId。使用这些值,我在数据库中搜索它们的名称并返回一个 JSONArray。

JSON Input: [{"studentId":"2","class":"2a","dbname":"testDb"}]
<?php

 $jsonString = $_POST['json'];  //see comment below

 $jArray = json_decode($jsonString, true);

 $conn = mysql_connect('localhost', 'user', 'pwd' );

mysql_select_db('dbname', $conn);

foreach( $jArray as $obj ){
    $className = $obj['class'];   //String
    $id= $obj['studentId'];       //int

    $result = mysql_query("SELECT name FROM student WHERE class='$className' AND id='$id'");

    $e=mysql_fetch_assoc($result);    //will only fetch 1 row of result
    $output[]=$e;


}

      echo (json_encode($output));

?>

安卓

HttpClient client = new DefaultHttpClient();
HttpResponse response;
try{
 HttpPost post = new HttpPost("http://abc/getName.php");
 List<NameValuePair> nVP = new ArrayList<NameValuePair>(2);  
 nVP.add(new BasicNameValuePair("json", studentJson.toString()));  //studentJson is the JSON input

//student.Json.toString() produces the correct JSON [{"studentId":"2","class":"2a","dbname":"testDb"}]

 post.setEntity(new UrlEncodedFormEntity(nVP));
 response = client.execute(post);
if(response!=null){
//process data send from php
}  
}

已解决:请参阅下面的答案

最佳答案

已解决:终于明白问题出在哪里了。从 Android 发布到 PHP 脚本后,我的 JSONArray 变为 [{\"studentId\":"2\",\"class\":\"2a\",\"dbname\":\"testDb\"}] 要删除“\”,使用 PHP 命令 stripslashes 调试了 4 小时!

希望这对那些想要在 Android 和 PHP 之间发送和检索数据的人来说是一个很好的指南

关于php - 将 JSONArray 从 Android 传递到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7503878/

相关文章:

android - 按下菜单按钮时应用程序崩溃

json - 如何计算 JSON 数组的平均值,然后四舍五入到小数点后一位

javascript - 通过 JavaScript/JQuery 下载 JSON 文件 - HTTP 状态正常 - JQuery 错误

php - Woocommerce 更新订单行项目小计

php - 为什么我不能在 nginx 中拥有自己的自定义根指令

php - 电子邮件正文和标题在 Laravel 中不起作用

php - MYSQL 将行提取到页面中

android - 将目标 SDK 更新到 android P 后 APK 安装失败

Android Support v4 版本 22.2.0 无法解析 FragmentActivity

java - 使用 jersey 客户端编写 POST 请求