2016-11-16 6 views
0

私はJavaScriptでjsonとして解析されるphpで配列を作成しようとしています。これはajax呼び出しで行います。 $empty = array()でインスタンス化された配列の最初のインデックスが{"0":[{..values here..}], "success":true}として返されることに気付きました。理想的には、reply.datareply.successを使用してアクセスします。返信成功は動作しますが、最初のインデックスとして0を持たない配列を作成する方法を見つけることはできません。キー値を持つ空の配列を作成する

マイPHP側のコード:私はそれが

{"0":[{"room_id":"20","host_id":"","resp_id":"","offer":"","answer":"","status":"0"}],"success":true} 

答えて

1

使用これを返す何ジャバスクリプト

success: function(data){ 
     data = JSON.parse(data); 
     if(data.success==true){ //able to access success with "data.success" 
      //there is an empty 
      $scope.conn = "connecting to room"; 
      console.log(data.data.room_id); //does not work because index is 0 
      console.log(JSON.stringify(data)); 

の中からアクセス

$result = array(); 
    $record = array(); 
    $resp = mysqli_query($this->conn, $sql); 
    if(mysqli_num_rows($resp)>0){ 
     while($row = mysqli_fetch_assoc($resp)){ 
      $record = array(); 
      foreach($row as $key => $val){ 
       $record[$key] = $val; 
      } 
      array_push($result,$record); 
      unset($record); 
     } 
     //return json_encode($result, JSON_PRETTY_PRINT); 
     return $result; 

$result = array(); 
$resp = mysqli_query($this->conn, $sql); 
if(mysqli_num_rows($resp)>0){ 
    while($row = mysqli_fetch_assoc($resp)){ 
     foreach($row as $key => $val){ 
      $result["data"][$key] = $val 
     } 
    } 
} 
//return json_encode($result, JSON_PRETTY_PRINT); 
return $result; 
+0

これは私の質問に答えましたが、返信機能を使って返信する必要がありますので、 、...}}]、 "success":true} 'なぜ配列を返すように見えますか? php reply func: 'public function reply($ success、$ data){ $ reply = array(); if(sizeof($ data)!= 0){ foreach($ data = $ val){ $ reply ['reply'] [$ key] = $ val; } } return json_encode($ reply); } ' –

+1

数字キーを持ち、数字で始まる「0」で始まり数字(つまり1,3,5)に隙間がないphp配列は、json_encodeの配列に変換されます。これはJSの中で同じものを使うことができるので、かなり標準的です。 'JSON_FORCE_OBJECT'定数をjson_encodeに渡すこともできます。 –

1

あなたはむしろプロセスを複雑にしていると思います。

$ rowを配列にロードするだけでforeachループは不要です。

public function xxx() 
{ 
    $result = array(); 
    $resp = mysqli_query($this->conn, $sql); 
    if(mysqli_num_rows($resp)>0) { 
     $result['success'] = 'true'; 

     while($row = mysqli_fetch_assoc($resp)){ 
      $result['data'][] = $row; 
     } 

    } else { 
     $result['success'] = 'false'; 
    } 
    return $result; 
} 

// instantiate object 
//$obj = new Whatever the class is called() 
echo json_encode($obj->xxx()); 
関連する問題