【问题标题】:Issues in json_encode [duplicate]json_encode 中的问题 [重复]
【发布时间】:2017-03-17 13:47:38
【问题描述】:

我有这个数组:

$array = [
  "stored_fields" => ["id"], 
  "match_all" => []
];

我想要:

{"stored_fields":["id"],"match_all":{}}

但是,当我打电话时:

echo json_encode($array);

我明白了:

{"stored_fields":["id"],"match_all":[]}

如果我使用:

echo json_encode($array, JSON_FORCE_OBJECT);

我明白了:

{"stored_fields":{"0":"id"},"match_all":{}}

我能做什么?

【问题讨论】:

    标签: php json


    【解决方案1】:

    可能有更好的方法,但你可以强制一个对象:

    $array = [
      "stored_fields" => ["id"], 
      "match_all" => (object)[]
    ];
    

    您也可以使用(object)null。其他任何事情都会导致{"scalar":someting}。另一个选项是new stdClass。

    【讨论】:

      猜你喜欢
      • 2011-08-28
      • 2011-06-14
      • 2010-12-03
      • 1970-01-01
      • 2011-11-09
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多