AJAX响应与奇怪的JSON格式

时间:2013-01-23 01:24:17

标签: jquery json

你好我有一个PHP脚本,它从一个表中查找用户的所有电话号码,然后根据该电话号码列表在另一个表中查找他的信息。

PHP脚本:

$intUserID = $_POST['intUserID_PHP']; //This is the user ID 
$arrayUserPhoneNumbers = $_POST['arrayUserPhoneNumbers'];//this is an array of all the user's phone numbers.
  try {     
        $DBC  = new PDO("pgsql:host=$host;port=$port;dbname=$dbname;user=$user;           password=$password");//All my DB connection is well set.
        $query1 = "SELECT phones FROM usersphones WHERE id=".$intUserID;
        $sth = $DBC->prepare($query1);
        $sth->execute();
        $result = $sth->fetchAll();
        $i = 0;
           foreach ($result as $data) {
             $query2 = "SELECT txtshare,dtzserver,adress,issue FROM tbluserinfo WHERE  phone='".$data['phones']."'";
             $sth = $DBC->prepare($query2);
             $sth->execute();
             $result2 = $sth->fetchAll();
             echo json_encode($result2);
             $i++;  
           }    
}           
catch(PDOException $e) {
     echo 'Error';   
}

这是我正在使用的JQuery代码:

$.ajax({
    type: "POST",
    url: "getinfo.php",              
    dataType:'json',
    data: {arrayUserPhoneNumbers : arrayUserPhoneNumbers,intUserID : intUserID},
success: function(data) {
}
});

我的问题是: 我收到很多行,这只是最后一行,我从我的firebug控制台得到的JSON结果是:

[
    {
        "txtshare": "F",
        "0": "F",
        "dtzserver": "2013-01-05 00:32:55.311037+00",
        "1": "2013-01-05 00:32:55.311037+00",
        "phone": "+33522988655",
        "2": "+33522988655",
        "issue": "Lost my smartphone",
        "3": "Lost my smartphone"
    }
]

我的JSON有效,但我不知道为什么在这个结果中有重复数据的那些“0”,“1”,“2”和“3”索引?在我的表中我只有txtshare,dtzserver,电话和问题字段。 我希望它是这样的:

[
        {
            "txtshare": "F",
            "dtzserver": "2013-01-05 00:32:55.311037+00",
            "phone": "+33522988655",
            "issue": "Lost my smartphone",
        }
 ]

提前致谢。

1 个答案:

答案 0 :(得分:0)

您可能会看到返回的JSON包含key =>值对和数组索引格式,所以它由你来选择任何1。     访问:http://php.net/manual/en/function.json-encode.php

echo "Sequential array".PHP_EOL;
$sequential = array("foo", "bar", "baz", "blong");
var_dump(
 $sequential,
 json_encode($sequential)
);

echo PHP_EOL."Non-sequential array".PHP_EOL;
$nonsequential = array(1=>"foo", 2=>"bar", 3=>"baz", 4=>"blong");
var_dump(
 $nonsequential,
 json_encode($nonsequential)
);

echo PHP_EOL."Sequential array with one key unset".PHP_EOL;
unset($sequential[1]);
var_dump(
 $sequential,
 json_encode($sequential)
);

输出:

顺序数组 array(4){   [0] =>   string(3)“foo”   [1] =>   string(3)“bar”   [2] =>   string(3)“baz”   [3] =>   string(5)“blong” } string(27)“[”foo“,”bar“,”baz“,”blong“]”

非顺序数组 array(4){   [1] =>   string(3)“foo”   [2] =>   string(3)“bar”   [3] =>   string(3)“baz”   [4] =>   string(5)“blong” } string(43)“{”1“:”foo“,”2“:”bar“,”3“:”baz“,”4“:”blong“}”

一个键未设置的顺序数组 array(3){   [0] =>   string(3)“foo”   [2] =>   string(3)“baz”   [3] =>   string(5)“blong” } string(33)“{”0“:”foo“,”2“:”baz“,”3“:”blong“}”

相关问题