从Android传递JSONArray到PHP

时间:2011-09-21 17:17:45

标签: php android json arrays

我已经阅读了许多关于PHP和JSONArray循环的其他问题。我正在通过我的Android设备向他们的班级和studentId发送不同学生的JSONArray值。使用这些值,我在数据库中搜索它们的名称并返回一个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));

?>

的Android

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
}  
}

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

2 个答案:

答案 0 :(得分:6)

已解决:最后了解问题所在。从Android发布到PHP脚本后,我的JSONArray变为[{\"studentId\":"2\",\"class\":\"2a\",\"dbname\":\"testDb\"}]要删除“\”,请使用PHP命令stripslashes花4个小时进行调试!

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

答案 1 :(得分:1)

这是你的问题:

print_r(json_decode('[{"regNo":"2","class":"2a","dbname":"TestData"}]',true));

返回Array ( [0] => Array ( [regNo] => 2 [class] => 2a [dbname] => TestData ) ),表示已解码的json放在数组

使用array_shift(json_decode($jsonString, true));删除父数组。