jQuery中的php数组循环:警报[object object]

时间:2018-08-29 16:09:55

标签: javascript php jquery

我在php中有一个名为$ post_id的数组

$post_id = $wpdb->get_results("SELECT DISTINCT user_id FROM $wpdb->pmpro_membership_orders");

我在jQuery中遍历PHP数组

 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));

            }
        });

    });

,我总是处于警戒状态[对象对象]。和id_user alert,但他应该显示5个“ yess”和与id user相等的id。

1 个答案:

答案 0 :(得分:1)

json_encode所做的工作将转换为json格式的文本字符串

示例:

$post_id = array(array("id" => 1), array("id" => 2));

$json_string = json_encode($post_id);

// json_string = "[{"id" => 1, "id" => 2}]"

使用Java脚本

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