drh19790711 2015-05-17 22:33
浏览 44
已采纳

Android PHP Json

I have looked around for over a few hours and most of the post I see are from way back when, so maybe I just don't understand or it might be outdated. I have two problems.

I have an Json object and Json Array that comes out like this:

    {"command":"update", "Data":["first data","second data","third data","fourth data"]}     

I want it it to read like this:

{"command":"update", "Data":[{"1":"first data"},{"2":"second data"},{"1":"third data"},{"2":"fourth data"}]}

I am unclear how to add the 1 & 2 so I can know what to pull on the php side.And it might not be the proper format either, but you will get an ideal. Android code:

JSONObject parent = new JSONObject();
JSONArray child = new JSONArray();
child.put("first data");
child.put("second data");
parent.put("Data", child);

Next problem on my php side is pulling the data so I can put it into my database and I am unsure exactly how this is done:

// DECODE OUR JSON FROM ANDROID
$data = json_decode(file_get_contents('php://input'), true);

// FOR LOOP TO INSERT DATA INTO DATABASE
for($i=0; $i<count($obj['Data']); $i+=2) 
{
     // need to get 1 & 2 values to insert into database
     //$first = NEED VALUE OF 1
     //$second = NEED VALUE OF 2
     // mysqli statement to insert into database
     $Q = "INSERT INTO `DATA_TABLE` (data1, data2) VALUES ('$first', '$second');
     mysqli_query($conn, $Q);
}
  • 写回答

1条回答 默认 最新

  • douya2433 2015-05-17 23:15
    关注

    Change your code to

    JSONObject parent = new JSONObject();
    JSONArray child = new JSONArray();
    child.put({ "1", "first data" });
    child.put({ "2", "second data" });
    

    But I would more likely store your data as an object inside an array with each object being one insert into your database.

    JSONObject parent = new JSONObject();
    JSONArray child = new JSONArray();
    JSONObject item1 = new JSONObject();
    JSONObject item2 = new JSONObject();
    ...
    item1.name = "Item 1 name";
    item1.rating = "Item 1 rating";
    ...
    child.put(item1);
    child.put(item2);
    

    Then you can iterate through each item in the data array and know that it contains all the data you need to populate your database.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路