将php数组传递给ajax

I have this array:

    $users = array();
// Finally, loop over the results
foreach( $select as $email => $ip )
{
    $users[$email] = $ip;
}

Now i want to pass this array to ajax and print in another script:

$html="<center><a href=\"#\" id=\"check_spam\" onclick=\"$.ajax({type: 'POST', url: 'mcheck.php', data:'users=$users', success: function(data){ $('#results').html(data);}});\">Check users for spam</a></center>";

mcheck.php

echo $_POST['users'];

This code does not work. How can i do this?

The Best way is to encode array into JSON format.

In PHP:

$users_json = json_encode($users);

// To decode in javascript

var obj = JSON.parse(json_str);

if u want to pass php array to js you can json_encode the array to do that.

$html="<center><a href=\"#\" id=\"check_spam\" onclick=\"$.ajax({type: 'POST', url: 'mcheck.php', data:'users=".json_encode($users)."', success: function(data){ $('#results').html(data);}});\">Check users for spam</a></center>";

As Sergiu Costas pointer out, the best way is to JSON encode it and then decode, but you can also try:

$html="<center><a href=\"#\" id=\"check_spam\" onclick=\"$.ajax({type: 'POST', url: 'mcheck.php', data: '" . http_build_query(array('users' => $users)) . "', success: function(data){ $('#results').html(data);}});\">Check users for spam</a></center>";

If your $users array is:

$users = array( array('email' => 'a@email.com'), array('email' => 'b@email.com')));

then http_build_query('users' => $users) will generate:

users%5B0%5D%5Bemail%5D=a%40email.com&users%5B1%5D%5Bemail%5D=b%40email.com

which is the url-encoded version of:

 users[0][email]=a@email.com&users[1][email]=b@email.com

which will be decoded back to array in mcheck.php