2017-10-05 270 views
0

我正在使用phil sturgeon的codeigniter休息。如何在json codeigniter rest服務器中返回json對象的編碼json

我想返回一個JSON對象,其中包含另一個JSON對象。

我的代碼看起來像這樣

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); 
     }*/ 
    } 

它沒有顯示任何結果......如果我這樣做,而不在其他PHP對象加入PHP對象,它讓我看到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);