简体   繁体   English

Codeigniter / PHP /将对象转换为JSON

[英]Codeigniter / PHP/ convert Object to JSON

I cannot fully understand what I have below and I need to convert it to JSON. 我无法完全理解下面的内容,需要将其转换为JSON。

My guess is I have an array of 16 starting from 0 to 15. Item 0 is an object by ["id"]=>"1", ["ip_address"]=>"127.0.0.3", etc looks like an associative array. 我的猜测是,我有一个从0到15开始的16数组。项目0是[[id]] =>“ 1”,[“ ip_address”] =>“ 127.0.0.3”的对象,看起来像一个关联对象数组。 Confused. 困惑。

Second question when I decode($abovearray) I get something but doesn't look like JSON! 当我解码时的第二个问题($ abovearray)我得到了一些东西,但看起来却不像JSON! Any help much appreciated. 任何帮助,不胜感激。

Here is a sample of my array output that I need to convert to 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~]
              }
     ...}

Try like this... 这样尝试...

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

On controller 在控制器上

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

Should out put 应该放出来

[{"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>

It look like data in view for js but in php use this in PHP 它看起来像JS鉴于数据,但在PHP中使用这个在PHP

  $jsonEncode  =  json_encode($array);

in JS How to decode a JSON string? 在JS中 如何解码JSON字符串?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM