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
        });
    });
1
  • Show us your jQuery code. Commented Aug 19, 2013 at 4:54

1 Answer 1

2

First suppose that your array is stored in $books variable.

$books = json_enconde($books);

Then we have received correctly that array.

$.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>');
        });
    }
 }
});

Hope it helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.