如何在foreach中将数组回显到从JSON到字符串的转换

时间:2022-09-15 11:53:09

I want to pass an array into a database but i'm getting a notice and the echo is not working to print out the string I want.

我想要将数组传递到数据库中,但是我得到了一个通知,而echo并不能打印我想要的字符串。

Notice: Array to string conversion on line 7 ( echo $item; )

注意:第7行中的数组到字符串转换(echo $item;)

How do I capture the data being sent into a database?

如何捕获发送到数据库中的数据?

Where the arrays are sent by author and their books. e.g.

数组是由作者及其书籍发送的。如。

[{"name":"Book1","books":["Book1.1"]},{"name":"Book2","books":["Book2.1","Book2.2"]}]

[{“名称”:“Book1”,“书”:[" Book1.1 "]},{“名称”:“Book2”,“书”:[“Book2.1”、“Book2.2”]}]

This is next.php where the data is being passed and not being echoed.

这是下一个。在php中,数据正在被传递而没有被回显。

<?php
var_dump($_POST);

$data = json_decode(stripslashes($_POST['arr']), true);

foreach($data as $item){
   echo $item;
   // insert to db
}

?>

The alert is giving me the return data from next.php in the sendToServer function (see snippet).

警报告诉我从next返回的数据。sendToServer函数中的php(请参见代码片段)。

success: function(data) {
    alert(data);
}

Full code in the snippet:

完整代码片段:

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
  <style type="text/css">
    <!-- #main {
      max-width: 800px;
      margin: 0 auto;
    }
    -->
  </style>
</head>

    <body>
    <div id="main">
        <h1>Add or Remove text boxes with jQuery</h1>
        <div class="my-form">
<!--            <form action="next.php" method="post">-->
                <button onclick="addAuthor()">Add Author</button>
                <br>
                <br>
                <div id="addAuth"></div>
                <br>
                <br>
                <button onclick="submit()">Submit</button>
<!--            </form>-->
        </div>

        <div id="result"></div>
    </div>

    <script type="text/javascript">
        var authors = 0;

        function addAuthor() {
        authors++;
            var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
            $("#addAuth").append(str);
        }

        var count = 0;

        function addMore(id) {
            count++;
            var str = 
            '<div id="bookDiv' + count + '">' 
                + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' 
                + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>'
            + '</div>';
            $("#" + id).append(str);
        }
        
        function removeDiv(id) {
            $("#" + id).slideUp(function() {
                $("#" + id).remove();
            });
        }
        function submit() {
            var arr = [];
            for (i = 1; i <= authors; i++) {
                var obj = {};
                obj.name = $("#author" + i).val();
                obj.books = [];
                $(".auth" + i).each(function() {
                var data = $(this).val();
                    obj.books.push(data);
                });
                arr.push(obj);
            }
            sendToServer(arr);
            //$("#result").html(JSON.stringify(arr));
        }

        function sendToServer(data) {
            $.ajax({
                type: "POST",
                data: {
                    arr: JSON.stringify(data)
                },
                url: "next.php",
                success: function(data) {
                        alert(data);
                }
            });
            
        }
    </script>
</body>

</html>

2 个解决方案

#1


2  

you are getting Notice: Array to string conversion on line 7 ( echo $item; ) because you are going to print array. You can't print array whereas you can do a string so. To do like that use something like this.

您将注意到:第7行中的数组到字符串转换(echo $item;)因为你要打印数组。你不能打印数组,但你可以打印字符串。用这样的方法来做。

<?php
var_dump($_POST);

$data = json_decode(stripslashes($_POST['arr']), true);

for ($i=0;$i<count($data);$i++){
    echo "Name: ".$data[$i]['name']. "<br/>";
    echo "Books: ";
    foreach($data[$i]['books'] as $book){
        echo $book . " ";
    }
    echo "...............<br/>";    

    // insert to db example
    $sql="INSERT INTO author(id, name) VALUES (NULL, '".$data[$i]['name']."')";
    //execute query and get last insert id
    //$author_id=last insert id
    foreach($data[$i]['books'] as $book){
        $sql="INSERT INTO author_books(id, author_id, book_name) VALUES (NULL,'$author_id', '$book')";
        //execute query
    }

}

?>

#2


2  

This is what you have form POST:

这是你的表格:

    [
        {
            "name":"Book1",
            "books": [
                "Book1.1"
            ]
        },{
            "name":"Book2",
            "books": [
                "Book2.1",
                "Book2.2"
            ]
        }
    ]

To read the data using a foreach you need to do:

使用foreach来读取数据:

foreach($data as $item) {
    echo "Name: " . $item["name"] . "<br>";
    echo "Books: " . implode(", ", $item["books"]) . "<br>";

    // Other way..

    echo "Name: " . $item["name"] . "<br>";
    echo "Books: <br>";
    foreach($book as $item["books"])
        echo $book . "<br>";
}

By this foreach you can manipulate your data and build your INSERT statement to input data to database.

通过这种方法,您可以操纵数据并构建INSERT语句,将数据输入到数据库。

#1


2  

you are getting Notice: Array to string conversion on line 7 ( echo $item; ) because you are going to print array. You can't print array whereas you can do a string so. To do like that use something like this.

您将注意到:第7行中的数组到字符串转换(echo $item;)因为你要打印数组。你不能打印数组,但你可以打印字符串。用这样的方法来做。

<?php
var_dump($_POST);

$data = json_decode(stripslashes($_POST['arr']), true);

for ($i=0;$i<count($data);$i++){
    echo "Name: ".$data[$i]['name']. "<br/>";
    echo "Books: ";
    foreach($data[$i]['books'] as $book){
        echo $book . " ";
    }
    echo "...............<br/>";    

    // insert to db example
    $sql="INSERT INTO author(id, name) VALUES (NULL, '".$data[$i]['name']."')";
    //execute query and get last insert id
    //$author_id=last insert id
    foreach($data[$i]['books'] as $book){
        $sql="INSERT INTO author_books(id, author_id, book_name) VALUES (NULL,'$author_id', '$book')";
        //execute query
    }

}

?>

#2


2  

This is what you have form POST:

这是你的表格:

    [
        {
            "name":"Book1",
            "books": [
                "Book1.1"
            ]
        },{
            "name":"Book2",
            "books": [
                "Book2.1",
                "Book2.2"
            ]
        }
    ]

To read the data using a foreach you need to do:

使用foreach来读取数据:

foreach($data as $item) {
    echo "Name: " . $item["name"] . "<br>";
    echo "Books: " . implode(", ", $item["books"]) . "<br>";

    // Other way..

    echo "Name: " . $item["name"] . "<br>";
    echo "Books: <br>";
    foreach($book as $item["books"])
        echo $book . "<br>";
}

By this foreach you can manipulate your data and build your INSERT statement to input data to database.

通过这种方法,您可以操纵数据并构建INSERT语句,将数据输入到数据库。