Loop through values of a JSONArray in php

前提是你 提交于 2019-12-13 03:45:06

问题


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

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++;
}

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.


回答1:


Please try the below code.

<?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.



来源:https://stackoverflow.com/questions/55056910/loop-through-values-of-a-jsonarray-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!