2013-01-23 5 views
0

안녕하세요. 한 테이블에서 사용자의 모든 전화 번호를 찾아서 전화 번호 목록에 따라 다른 정보를 찾는 PHP 스크립트가 있습니다.이상한 JSON 형식의 AJAX 응답

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

내 질문은 : I 행을 많이 받고 있어요 이것이 마지막입니다 JSON 결과는 firebug 콘솔에서 가져옵니다.

[ 
    { 
     "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", 
     } 
] 

감사합니다.

답변

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

OUTPUT :

순차 배열 어레이 (4) { [0] => 캐릭터 (3) "foo에" [1] => 문자열 (3) "바" [2] => 캐릭터 (3) "바즈" [3] => 문자열 (5) "blong" } 문자열 (27) "["foo에 ","바 ","바즈 ","blong "]"

비 순차적 배열 어레이 (4) { [1] => 캐릭터 (3) "foo에" [2] => 캐릭터 (3) "바" [3] => 문자열 (3) "baz" [4] => 문자열 (5) "blong" } "{"1 ":"foo ","2 ":"bar ","3 ":"baz " "4" "blong"} "

한 키 해제 배열

순차 어레이 (3) { [0] => 캐릭터 (3)"foo에 " [2] => 문자열 (3) "baz" [3] => 문자열 (5) "blong" 문자열 "("0 ":"foo ","2 ":"baz ","3 ":"blong "}"