【问题标题】:Codeigniter / PHP/ convert Object to JSONCodeigniter / PHP / 将对象转换为 JSON
【发布时间】:2017-01-13 02:00:51
【问题描述】:

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

我的猜测是我有一个从 0 到 15 的 16 个数组。第 0 项是 ["id"]=>"1"、["ip_address"]=>"127.0.0.3" 等的对象就像一个关联数组。使困惑。

解码时的第二个问题($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~]
              }
     ...}

【问题讨论】:

  • 你拥有的是一个对象数组(不是字符串数组)
  • 我看到了两个观察结果,但没有明确的问题。

标签: php arrays json codeigniter


【解决方案1】:

试试这样...

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

【讨论】:

    【解决方案2】:

    在控制器上

    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>
    

    【讨论】:

      【解决方案3】:

      它看起来像 js 视图中的数据,但在 php 中使用它 在 PHP 中

        $jsonEncode  =  json_encode($array);
      

      在 JS 中 How to decode a JSON string?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-09
        • 1970-01-01
        • 1970-01-01
        • 2017-06-16
        • 1970-01-01
        • 2017-05-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多