[英]Passing JSONArray to PHP from Android
我已經閱讀了許多關於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
}
}
已解決:見下面的答案
解決:終於明白了問題是什么。 從Android發布到PHP腳本后,我的JSONArray變為[{\\"studentId\\":"2\\",\\"class\\":\\"2a\\",\\"dbname\\":\\"testDb\\"}]
刪除“\\”,使用PHP命令stripslashes
花了4個小時調試!
希望這對那些想要在Android和PHP之間發送和檢索數據的人來說是一個很好的指南
這是你的問題:
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));
刪除父數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.