PHP json_encode - JSON_FORCE_OBJECT mixed object and array output

前端 未结 3 1114
谎友^
谎友^ 2020-12-30 19:16

I have a PHP data structure I want to JSON encode. It can contain a number of empty arrays, some of which need to be encoded as arrays and some of which need to be encoded a

相关标签:
3条回答
  • 2020-12-30 19:39

    Create bar1 as a new stdClass() object. That will be the only way for json_encode() to distinguish it. It can be done by calling new stdClass(), or casting it with (object)array()

    $foo = array(
      "bar1" => new stdClass(), // Should be encoded as an object
      "bar2" => array() // Should be encoded as an array
    );
    
    echo json_encode($foo);
    // {"bar1":{}, "bar2":[]}
    

    OR by typecasting:

    $foo = array(
      "bar1" => (object)array(), // Should be encoded as an object
      "bar2" => array() // Should be encoded as an array
    );
    
    echo json_encode($foo);
    // {"bar1":{}, "bar2":[]}
    
    0 讨论(0)
  • 2020-12-30 19:40

    Same answer, for php7+ and php 5.4.

    $foo = [
      "bar1" => (object)["",""],
      "bar2" => ["",""]
    ];
    

    echo json_encode($foo);

    0 讨论(0)
  • 2020-12-30 19:48

    There answer is no. There is no way for the function to guess your intent as to which array should be array and which should be objects. You should simply cast the arrays you want as object before json_encoding them

    0 讨论(0)
提交回复
热议问题