2017-01-13 154 views
0

我无法完全理解下面的内容,我需要将其转换为JSON。Codeigniter/PHP /将对象转换为JSON

我的猜测是我有一个16到16的数组。看起来像一个关联数组。困惑。

第二个问题,当我解码($ abovearray)我得到的东西,但看起来不像JSON!任何帮助非常感谢。

以下是我需要转换为JSON的数组输出示例。

array(16) { 
      [0]=> object(stdClass)#31 (25) { 
       ["id"]=> string(1) "1" 
       ["ip_address"]=> string(9) "127.0.0.3" 
       ["username"]=> string(13) "administrator" 
       [~snip~] 
       } 
      [1]=> object(stdClass)#33 (25) { 
       ["id"]=> string(1) "2" 
       ["ip_address"]=> string(15) "111.111.111.201" 
       ["username"]=> string(0) "" 
       [~snip~] 
       } 
    ...} 
+0

你有什么是对象的数组(不是字符串数组) – bansi

+0

我看到两种意见,但没有明确的问题。 – ryyker

回答

0

尝试像这样...

$json = json_encode($array,JSON_FORCE_OBJECT); 
echo $json; 
0

在控制器

public function test() { 
    $data = array(); 

    $data[] = array(
     'id' => '1', 
     'ip_address' => "127.0.0.3", 
     'username' => 'administrator' 
    ); 

    $data[] = array(
     'id' => '2', 
     'ip_address' => "111.111.111.201", 
     'username' => '' 
    ); 

    echo json_encode($data); 
} 

应该出来把

[{"id":"1","ip_address":"127.0.0.3","username":"administrator"},{"id":"2","ip_address":"111.111.111.201","username":""}] 

<script type="text/javascript"> 
$('#commit').click(function(e){ 
    e.preventDefault(); 
    $.ajax 
    ({ 
    type: 'get', 
    url: "<?php echo base_url('welcome/test');?>", 
    dataType: 'json', 
    success: function(response) 
    { 
     alert(response['username']) // you may need to use the jquery each function 

     https://api.jquery.com/each/ 

    }); 
}); 
</script>