0

I have a multidimensional array generated using PHP as below:

$result = array(
        array(
            'bookID' => '1',
            'bookName' => 'Book1',
            'bookAuthor' => 'Author1',
            'bookISBN' => 'ISBN1',
            'bookStatus' => 'Available'
        ),
        array(
            'bookID' => '2',
            'bookName' => 'Book2',
            'bookAuthor' => 'Author2',
            'bookISBN' => 'ISBN2',
            'bookStatus' => 'On Loan'
        ),
        array(
            'bookID' => '3',
            'bookName' => 'Book3',
            'bookAuthor' => 'Author3',
            'bookISBN' => 'ISBN3',
            'bookStatus' => 'On Loan'
        ),
        array(
            'bookID' => '4',
            'bookName' => 'Book4',
            'bookAuthor' => 'Author4',
            'bookISBN' => 'ISBN4',
            'bookStatus' => 'Available'
        ),
    );
echo json_encode($result);

And I have a HTML file that is using $.getJSON to get that array. What I am now trying to do is create a table using that array, such that it looks something like this:

+---+-------+---------+-------+-----------+
| 1 | Book1 | Author1 | ISBN1 | Available |
+---+-------+---------+-------+-----------+
| 2 | Book2 | Author2 | ISBN2 | On Loan   |
+---+-------+---------+-------+-----------+
| 3 | Book3 | Author3 | ISBN3 | On Loan   |
+---+-------+---------+-------+-----------+
| 4 | Book4 | Author4 | ISBN4 | Available |
+---+-------+---------+-------+-----------+

I have tried using $.each() and foreach() including suggestions from other SO questions but I cannot seem to get it to work at all. Can anyone help?

My jQuery code at the moment:

$(document).ready(function() {
        // var query = $('#query').val();
        $.getJSON('[url of PHP file above]', function(data){
            // Do something to create table
        });
    });
4

1 回答 1

2

首先假设您的数组存储在 $books 变量中。

$books = json_enconde($books);

然后我们正确地收到了该数组。

$.ajax({
 ...
 success: function(data){
    var $table = $('<table />');
    $.each(data, function(i, item){
        var $tr = $('<tr />');
        $tr.appendTo($table);
        $.each(a, function(subitem) {
            $tr.append('<td>'+ subitem + '</td>');
        });
    }
 }
});

希望能帮助到你!

于 2013-08-19T05:00:26.120 回答