【问题标题】:Android PHP Json安卓 PHP json
【发布时间】:2015-05-17 22:33:08
【问题描述】:

我已经环顾了几个小时,我看到的大部分帖子都是很久以前的,所以也许我只是不明白,或者它可能已经过时了。我有两个问题。

我有一个像这样出来的 Json 对象和 Json 数组:

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

我希望它看起来像这样:

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

我不清楚如何添加 1 和 2,这样我就可以知道在 php 方面要拉什么。它可能也不是正确的格式,但你会得到一个理想的。安卓代码:

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

我的 php 方面的下一个问题是提取数据,以便我可以将其放入我的数据库中,但我不确定这是如何完成的:

// 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);
}

【问题讨论】:

    标签: php android arrays json object


    【解决方案1】:

    将代码更改为

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

    但我更可能将您的数据作为一个对象存储在一个数组中,每个对象都插入到您的数据库中。

    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);
    

    然后您可以遍历数据数组中的每个项目,并知道它包含填充数据库所需的所有数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 2015-09-06
      • 2013-03-24
      • 1970-01-01
      • 2011-03-08
      • 2013-05-28
      • 1970-01-01
      相关资源
      最近更新 更多