Q:

PHP loop through jquery loop

I have this simple jQuery function: 
$(document).ready(function () {
    var books = {};
    books.id = '1';
    books.author = 'Bob';

    $.post('/index.php',
    {
       books: books
    },
    function(data, textStatus)
    {
       alert(data);  
    });
});

And this index PHP script:
<?php

  foreach($_POST['books'] AS $key) {
       echo ''.$key['id'].' is written by '.$key['author'].'';
  }

?>

I want to loop through the jQuery array and display the id and author of each key in the array. I don't know the correct way to access the values in the array. It seems I'm doing it wrong.

A:

You have misunderstood the difference between {} and [] in JavaScript:

{} is an object
[] is an array

In your case you should pass an array of book objects for this to work in your php script. 
Example:
var books = [
    {
        id: 1,
        name: "The Da Vinci Code",
        author: "Dan Brown"
    },
    {
        id: 1,
        name: "Gray Mountain: A Novel",
        author: "John Grisham"
    }
]

To add more elements to the array after it has been initialized, you can simply use push:
books.push({id: 3, name: "Avatar", author: "Lisa Fitzpatrick"});

Will output:
1 is written by Dan Brown
2 is written by John Grisham 
3 is written by Lisa Fitzpatrick

