【发布时间】:2011-11-22 03:56:26
【问题描述】:
我已经阅读了许多关于 PHP 和 JSONArray 循环的其他问题。我正在从我的 Android 设备发送不同学生的 JSONArray 值以及他们的班级和学生 ID。使用这些值,我在数据库中搜索它们的名称并返回一个 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
}
}
已解决:请参阅下面的答案
【问题讨论】:
-
使用您的 JSONArray 输入和
print_r($jArray);的输出更新您的帖子 -
我刚刚运行了这个,但首先对其进行了简化。设置
$jsonString = '[{"regNo":"2","class":"2a","dbname":"TestData"}]'然后在$id= $obj['studentId'];之后我做了echo "SELECT name FROM student WHERE class='$className' AND id='$id'"并且它起作用了。 (另外,我删除了对输出或 mysql 的任何引用)。尝试输出您的 JSON 对象(解码后)以确保它是一个数组,并且传入的 JSON 字符串没有格式错误。 -
正如@JasonMcCreary 之前所说,添加您获得的数据。将您的
var_dump($jsonString);和var_dump($jArray);输出添加到帖子中。也许 $jArray 是 null 左右...... -
谢谢大家,这就是问题所在,$jArray 为空... PHP 无法检索我的 JSONArray 输入
-
我已经编辑了我的问题以包含我在 JSONArray 输入中发送的部分