0

您好,我有一个 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",
        }
 ]

提前致谢。

4

1 回答 1

0

您可能会看到返回的 JSON 包含键 => 值对和数组索引格式,因此您可以从中选择任何 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" } 字符串(27) "["foo","bar","baz","blong"]"

非序列数组array(4) { [1]=> string(3) "foo" [2]=> string(3) "bar" [3]=> string(3) "baz" [4]=>字符串(5) "blong" } 字符串(43) "{"1":"foo","2":"bar","3":"baz","4":"blong"}"

一键序列数组 unset array(3) { [0]=> string(3) "foo" [2]=> string(3) "baz" [3]=> string(5) "blong" } string( 33) "{"0":"foo","2":"baz","3":"blong"}"

于 2013-01-23T08:08:32.510 回答