2016-06-28 88 views
0

下面是用户列表webservice的json响应的代码。Codeigniter中的Json响应

<?php if (! defined('BASEPATH')) exit('No direct script access allowed'); 
class Webservice extends CI_Controller 
{ 
     function list_user() 
     { 
       $result_login = $this->db->get('user_registration')->result(); 
       $response = array(); 
       $response ["success"] = 1;   
       $response ["message"] = "User List."; 
       foreach($result_login as $row) 
       { 
         $data = array(); 
         $data['User Id'] = $row->user_id; 
         $data['Name'] = $row->name; 
         $data['Email'] = $row->email; 
         $data['mobile_number'] = $row->mobile_number; 
         $data['Password'] = $row->password; 
         $output2 = json_encode(array('responsedata' => $data)); 
         echo $output2; 
       } 

     } 
} 
?> 

在我的代码中,如果我用json_encode中的$ response替换$ data,那么我无法获得$ data的值。 我以这种格式得到了json响应。 JSON响应。

{ 
     "responsedata": { 
        "User Id": "7", 
        "Name": "bhavin", 
        "Email": "[email protected]", 
        "mobile_number": "123456789", 
        "Password": "abc" 
    } 
} 

但我想要这种格式的json响应。

{ 
     "responsedata": 
     { 
     "success": 1, 
     "data": [ 
      { 
         "User Id": "7", 
         "Name": "test", 
         "Email": "[email protected]", 
         "mobile_number": "123456789", 
         "Password": "abc" 
      }, 
      { 
         "User Id": "8", 
         "Name": "test2", 
         "Email": "[email protected]", 
         "mobile_number": "123456789", 
         "Password": "abc" 
      } 
     ] 
     } 
    } 

回答

3

您需要安排你的阵列这样

我更新下面的代码

$array_of_event = array() 
foreach($result_login->result_array() as $row) 
{ 
$array_of_event[] = $row; 
} 
    $data['success'] = "1"; 
    $data['data'] = $array_of_event; //need to assign event here 
    $response['responsedata'] = $data; 

    echo json_encode($response); 
+0

我试着用上面的代码,但我不能得到结果。我在$ data ['data'] = $ array_of_event中遇到问题。我如何获取一个一个行,并在最后我使用json_encode进行编码。 – Bhavin