如何在JSON中构建多维数组并将其传递给ajax调用?

时间:2018-01-24 19:01:08

标签: php jquery json ajax multidimensional-array

我在使用多维数组时遇到了一些麻烦。我的php代码如下:

$result = array();
$count = 0;

    foreach($matches_lines as $lines){

        $match_user = $lines["signup_username"];
        $match_birth = $lines["signup_birth"];
        $match_city = $lines["signup_city"];
        $match_gender = $lines["signup_gender"];
        $match_os = $lines["signup_os"];
        $match_persontype = $lines["signup_persontype"];

        if("some check on the variables"){

            $result[$count] = array('username' => "$match_user", 'birth'=> "$match_birth", 'city' => "$match_city", 'gender' => "$match_gender", 'os' => "$match_os", 'persontype' => "$match_persontype");
            $count = $count + 1;
            }
        }       
    }
    echo json_encode($result);
}

虽然我的ajax请求看起来像这样:

$("#select_age").click(function(){
        $.ajax({
            method: "POST",
            url: "get_matches.php",
            dataType: "json",
            data: {
            min_search: $( "#slider-range" ).slider( "values", 0 ),
            max_search: $( "#slider-range" ).slider( "values", 1 )
            },
            success: function(data){
                var myvar = jQuery.parseJSON(data);
                window.alert(myvar)
            }
        });
});

var_dump($ result)应如下所示:

array(2) {
  [0]=>
  array(6) {
    ["username"]=>
    string(6) "giulia"
    ["birth"]=>
    string(10) "05/10/1990"
    ["city"]=>
    string(6) "Torino"
    ["gender"]=>
    string(1) "F"
    ["os"]=>
    string(7) "Windows"
    ["persontype"]=>
    string(4) "ENFP"
  }
  [1]=>
  array(6) {
    ["username"]=>
    string(7) "taiga27"
    ["birth"]=>
    string(10) "07/27/1998"
    ["city"]=>
    string(6) "Torino"
    ["gender"]=>
    string(1) "F"
    ["os"]=>
    string(7) "Windows"
    ["persontype"]=>
    string(4) "ISTP"
  }
}

当我到达var myvar = jQuery.parseJSON(data)时;我收到错误“在位置2的JSON中出现意外的令牌a”

我错了什么?如何在foreach中初始化正确的JSON多维数组?如何在ajax成功函数中检索一次数据?

1 个答案:

答案 0 :(得分:0)

一些注意事项:

您无需递增$count即可附加到数组。只需排除索引(见下文)。

您不需要将变量放在双引号内。简单地传递变量而不带任何引号。

您的示例代码有一些额外的结束括号,也许您在共享之前/之后有其他代码,但如果没有,您当然不需要这么多括号。

您不应该使用var_dump()来返回数据,只需{J}编码的结果字符串echo()(就像您的示例中所示)。

$result = array();

foreach($matches_lines as $lines){

        $match_user = $lines["signup_username"];
        $match_birth = $lines["signup_birth"];
        $match_city = $lines["signup_city"];
        $match_gender = $lines["signup_gender"];
        $match_os = $lines["signup_os"];
        $match_persontype = $lines["signup_persontype"];

        if( 1 == 1 ){ // replace with "some check on the variables"
            $result[] = array('username' => $match_user, 'birth'=> $match_birth, 'city' => $match_city, 'gender' => $match_gender, 'os' => $match_os, 'persontype' => $match_persontype);
        }
}

echo json_encode($result);