在PHP中循环遍历JSONArray的值 [英] Loop through values of a JSONArray in php

查看:77
本文介绍了在PHP中循环遍历JSONArray的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Android应用程序中有3个arrayLists.我通过android volley POST请求将它们发送到php,例如:

I have 3 arrayLists in android app. I am sending them to php via android volley POST request like:

public RequestPostBook(long id, ArrayList<String> bookNames, ArrayList<String> bookAuthors, ArrayList<String> subjects,
                           String date,Response.Listener<String> listener)
    {
        super(Method.POST, REGISTER_REQUEST_URL, listener, null);

        JSONArray bookNamesJSON = new JSONArray(Arrays.asList(bookNames));
        JSONArray bookAuthorsJSON = new JSONArray(Arrays.asList(bookAuthors));
        JSONArray subjectsJSON = new JSONArray(Arrays.asList(subjects));


        params = new HashMap<>();
        params.put("candidateId", id + "");
        params.put("bookName",bookNamesJSON.toString());
        params.put("authorName",bookAuthorsJSON.toString());
        params.put("subjectName",subjectsJSON.toString());
        params.put("reqDate",date);
    }

    @Override
    public Map<String, String> getParams() {
        return params;
    }

现在,我必须使用php中的arrayList中的值来执行一系列类似的查询.我正在php中尝试这个

Now I have to use the values in the arrayList in php to execute a series of similar queries. I am trying this in php:

$candidateId=$_POST["candidateId"];
$reqDate=$_POST["reqDate"];
$subjectName=json_decode($_POST["subjectName"]);
$bookName=json_decode($_POST["bookName"]);
$authorName=json_decode($_POST["authorName"]);
$i=0;
foreach($subjectName as $value)
{
    $subject=$subjectName[$i];
    $book=$bookName[$i];
    $author=$authorName[$i];

    $stmt = $conn->prepare("INSERT INTO BookRequisition VALUES (?,?,?,?,?);");

    $stmt->bind_param("dssss", $candidateId, $subject, $book, $author, $reqDate);

    $stmt->execute();

    $i++;
}

当我通过应用程序运行此程序时,这就是我在BookRequisition表中得到的内容:

When I run this through the app, this is what I am getting in my BookRequisition table:

12100116050(candidateId)    Array(subjectName)    Array(bookName)    Array(authorName)    2019-03-08(reqDate)

有人可以帮助我如何将正确的值发送到表吗?预先感谢.

Can anyone please help me on how to send the correct values to the table? Thanks in advance.

推荐答案

请尝试以下代码.

<?php

$candidateId = $_POST["candidateId"];
$reqDate = $_POST["reqDate"];
$subjectName = json_decode($_POST["subjectName"])[0];
$bookName = json_decode($_POST["bookName"])[0];
$authorName = json_decode($_POST["authorName"])[0];

foreach ($subjectName as $i => $subject) {
    $stmt = $conn->prepare("INSERT INTO BookRequisition VALUES (?,?,?,?,?);");
    $stmt->bind_param("dssss", $candidateId, $subject, $bookName[$i], $authorName[$i], $reqDate);
    $stmt->execute();
}

?>

注意:您应该对从设备发布的数据进行正确的验证.

Note: You should do the proper validation on the data posted from your device.

这篇关于在PHP中循环遍历JSONArray的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆