Reputation: 370
I have an array in php named $post_id
$post_id = $wpdb->get_results("SELECT DISTINCT user_id FROM $wpdb->pmpro_membership_orders");
I iterate through a PHP array in jQuery
jQuery(document).ready(function( $ ) {
var id_user = userSettings.uid ;
// alert(id_user);
var arrayFromPHP = <?php echo json_encode($post_id) ?>;
$.each(arrayFromPHP, function (i, elem) {
// do your stuff
if (id_user == JSON.stringify(elem)){
alert('yess');
alert(JSON.stringify(elem));
}
else{
alert(id_user);
alert(JSON.stringify(elem));
}
});
});
and i get always in my alert [object object]. and id_user alert , but he should show 5 'yess' and the id that he equal to id user.
Upvotes: 0
Views: 312
Reputation: 428
what json_encode does is convert to a text string in json format
example:
$post_id = array(array("id" => 1), array("id" => 2));
$json_string = json_encode($post_id);
// json_string = "[{"id" => 1, "id" => 2}]"
In Java script
var arrayFromPHP = <?php echo json_encode($post_id) ?>;
console.log(arrayFromPHP);
// arrayFromPHP = "[{"id" => 1, "id" => 2}]" <-- (string)
var arrayFromPHP = JSON.parse('<?php echo json_encode($post_id) ?>');
console.log(arrayFromPHP);
// arrayFromPHP = [{"id" => 1, "id" => 2}] <-- JavaScript Object|Array
Upvotes: 1