break; } } if ($isExist == false) { returnApiError('no exist this id'); exit(''); } $dataArr[$upIndex]['name'] = $name; $dataArr[$upIndex]['age'] = $age; $dataArr[$upIndex]['sex'] = $sex; $dataArr = array_filter($dataArr); //去删除数组中的空元素 $json_string = json_encode($dataArr); $ifSuccess = file_put_contents('data.json', $json_string); if ($ifSuccess != false) { returnApiSuccess($ifSuccess); } else { returnApiError('file put fail'); } function returnApiSuccess($msg = null) { //执行成功时返回 $result = array('flag' => 'success', 'msg' => $msg); print json_encode($result); } function returnApiError($msg = null) { //执行失败时返回 $result = array('flag' => 'error', 'msg' => $msg); print json_encode($result); }
//将相应的文件json字符串转为数组 for ($j = $beginSearchIndex; $j <= $endSearchIndex; $j++) { //通过用户传入的key,找到相对应的下标 if (intval($id) == intval($dataArr[$j]['key'])) { $isExist = true; break; } } if ($isExist == false) { returnApiError('no exist this id'); exit(''); } for ($i = $beginSearchIndex; $i <= $endSearchIndex; $i++) { if ($id == $dataArr[$i]['key']) { //当数组中的key与用户请求的id相等时 returnApiSuccess($dataArr[$i]); break; } } function returnApiSuccess($data = array()) { //请求成功时调用,返回数据。 $result = array('flag' => 'success', 'data' => array('id' => $data['key'], 'name' => $data['name'], 'sex' => $data['sex'], 'age' => $data['age'])); print json_encode($result); } function returnApiError($msg = null) { //请求失败时调用,返回失败信息 $result = array('flag' => 'error', 'msg' => $msg); print json_encode($result); }
<?php /** * Created by PhpStorm. * User: 杨柳 * Date: 2015/12/5 * Time: 17:43 */ $flag = $_GET['action']; $dataFile_json_string; //数据文件json字符串变量 $indexTable_json_string = file_get_contents('indexTable.json') or exit("Unable to open file!"); $indexTable_array = json_decode($indexTable_json_string, true); $dataFile_json_string = file_get_contents('data.json'); $dataFile_array = json_decode($dataFile_json_string, true); $dataFile_array = array_filter($dataFile_array); //去除所有数组中的空元素 returnApiSuccess($dataFile_array); function returnApiSuccess($data = array()) { //请求成功时调用,返回数据。 $result = array('flag' => 'success', 'data' => $data); print json_encode($result); } function returnApiError() { //请求失败时调用,返回失败信息 $result = array('flag' => 'error', 'msg' => '请求错误,请重试!'); print json_encode($result); }