我從我的Android應用程序發送JsonArray就象這樣:腓JSONArray解碼和執行數據庫操作
final JSONArray data = new JSONArray();
try{
for(int i = 0; i<contactsList.size(); i++){
JSONObject jobj = new JSONObject();
ObjectContacts ob = contactsList.get(i);
jobj.put("contactid", ob.getContact_id());
jobj.put("mobile", ob.getNumber());
data.put(jobj);
}
}
,我的服務器接收所產生的陣列。
[
{"contactid":"3","mobile":"(545) 454-5445"},
{"contactid":"1","mobile":"(880) 939-5212"},
{"contactid":"2","mobile":"822895456165"}
]
我需要從這個數組提取手機號碼並進行DB操作,如果這個手機號碼存在或不看。我如何訪問每個移動設備並執行查詢?查詢將包括尋找手機號碼的存在,如果它是真的,它將獲取屬於手機號碼的姓名,最後以JSONArray格式將數組返回給移動應用程序,該格式將包括聯繫人ID,手機號碼,狀態(是或否),名稱。
時間不會成爲問題,但有時數組可能包含300-400手機號碼,具體取決於用戶的聯繫方式。
更新
這裏是新的PHP代碼,我實現的:
$app->post('/getcontacts', function() use ($app) {
//Verifying the required parameters
verifyRequiredParams(array('data'));
//Creating a response array
$response = array();
//reading post parameters
$data = $app->request->post('data');
$data_array = json_decode($data);
foreach ($data_array as $obj) {
$res = array();
$db = new DbOperation();
$r = $db->checkContactExist($obj->mobile);
if($r){
$res["contactid"] = $obj->contactid;
$res["mobile"] = $obj->mobile;
$res["name"] = $obj->name;
$res["status"] = 'yes';
$res["image_small"] = $db->getImageSmall($obj->mobile);
} else {
$res["contactid"] = $obj->contactid;
$res["mobile"] = $obj->mobile;
$res["name"] = $obj->name;
$res["status"] = 'no';
$res["image_small"] = '';
}
}
$response["error"] = false;
$response["message"] = json_encode($res);
echoResponse(201, $response);
});
我從服務器得到響應:
{"contactid":"3","mobile":"(943) 101-9713","status":"no","image_small":""}
雖然應該有三個觸點,它可能只讀的。
如果我只是通過echo將傳入數據發送迴應用程序來檢查所有聯繫人是否到來,那麼它的工作原理是正確的。也許在循環中我添加了關於只有一個聯繫人的詳細信息。
第二次更新
有無通過將解決這個問題:
$final_res = array();
和foreach循環
$final_res[] = $res;
從而發送此回:
json_encode($final_res);
任何數據庫訪問我嘗試了一個循環,然後獲取手機號碼並執行數據庫查詢。但循環只運行一次,因爲count(JSONArray)只顯示1 –