2017-10-05 7 views
0

私はphil sturgeonによってcodeigniter restを使用しています。json codeigniter rest serverでjsonオブジェクトを使用してエンコードされたjsonを返す方法

別のJSONオブジェクトを含むJSONオブジェクトを返したいとします。私は他のPHPオブジェクトにPHPのオブジェクトを追加せずにこれを行う場合は

私のコードは、それがどんな結果を示していない。この

function volunteer_get() 
    { 
     if(!$this->get('id')) 
     { 
      $this->response(NULL, 400); 
     } 

     $this->load->model('user/users_model'); 

     $user = $this->users_model->get($this->get('id')); 
     $address = $this->address_model->getAddress($this->get('id')); 

     $user->address = $address; 

     $userJson = json_encode($user); 
     var_dump($userJson); 

     /*if($user && $user->auth_level == 1) 
     { 
      $this->response($userJson, 200); // 200 being the HTTP response code 
     } 
     else 
     { 
      $this->response(NULL, 404); 
     }*/ 
    } 

のように見える...、それは私にJSONを示しています!一般的に

D:\wamp\www\codeigniter\application\controllers\api\Users.php:37:string '{"user_id":"1","username":"abc","email":"abc","auth_level":"1","banned":null,"passwd":"abcdefg","passwd_recovery_code":"abcdefg","passwd_recovery_date":"2017-06-12 18:50:31","passwd_modified_at":"2016-11-18 21:20:30","last_login":"2017-08-30 15:10:36","created_at":"2016-09-02 12:01:46","modified_at":"2017-08-30 15:22:45","first_name":"aze","family_name":"'... (length=1354) 
+0

'$ user'配列やオブジェクトはありますか? 'echo gettype($ user);'を試して、それが何を示しているか教えてください。 – MonkeyZeus

答えて

2

、あなたはJSONオブジェクト(通常はPHPの辞書やオブジェクト)またはJSON 表現(文字列)を得たかどうかを確認する必要があります。

他の文字列に文字列を追加することはできません。また、文字列を辞書やオブジェクトに追加すると、JSONサブオブジェクトとして正しくエンコードされません。なぜなら、それは文字列であるからです。あなたが表現している場合

ので、あなたはデコードする必要があり、それ最初

// Here, $dataOne is a string, and $dataTwo is too. 
// we decode to array rather than to object (see manual for json_encode) 

$dataOneJSON = json_decode($dataOne, true); 

$dataTwoJSON = json_decode($dataTwo, true); 

$dataOneJSON['two'] = $dataTwoJSON; 

$result = json_encode($dataOneJSON); 

$this->response($result, 200); 
関連する問題