简体   繁体   English

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

[英]php array loop in jquery: alert [ object object]

I have an array in php named $post_id 我在php中有一个名为$ 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中的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));

            }
        });

    });

and i get always in my alert [object object]. 而且我总是处于警报状态[object object]。 and id_user alert , but he should show 5 'yess' and the id that he equal to id user. 和id_user alert,但他应显示5'yess'和与id user相等的id。

what json_encode does is convert to a text string in json format json_encode的作用是将其转换为json格式的文本字符串

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 用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM