2017-10-05 51 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);