0

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.

1
  • Show your research. Have you tried debugging this yourself? What is actually being tested by the if statement, and is it expected? SO is not a great debugger, so you are encourage to do this yourself first: ericlippert.com/2014/03/05/how-to-debug-small-programs Commented Aug 29, 2018 at 16:19

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Edit the answer for a better understanding

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.