Php 如何将对象转换为特定的JSON格式?

Php 如何将对象转换为特定的JSON格式?,php,json,object,Php,Json,Object,json_encode将对象转换为: { "height":10, "width":20, "depth":5 } 但我还需要它包含对象类名称: { "cuboid": { "height":10, "width":20, "depth":5 } } 希望这能帮到你。在这里,我们将json转换为array,并将其放入字段cuboid 您可以使用获取对象的类名 $json = json_encode(array(get_class($objec

json_encode将对象转换为:

{
  "height":10,
  "width":20,
  "depth":5
}
但我还需要它包含对象类名称:

{
  "cuboid":
  {
    "height":10,
    "width":20,
    "depth":5
  }
}

希望这能帮到你。在这里,我们将
json
转换为
array
,并将其放入字段
cuboid

您可以使用获取对象的类名

$json = json_encode(array(get_class($object) => $object));

json\u编码的规则

  • 如果您有一个对象,它将被编码为
    {'pro1':'value'}
  • 如果您有一个数组,它将被编码为
    ['value']
  • 如果您有一个字符串,它将被编码为
    “值”
注意:如果在php中有一个assoc数组,它将成为json中的一个对象!如果您有一个索引数组,它将是json中的一个数组。不要把索引和assoc混在一起

测试这个错误的做法:
echo json_encode(数组('foo'=>'bar',1,2))结果是错误的语法
{“kitten”:“test”,“0”:1,“1”:2}
(属性名称不应该是数字!!!)

所以,如果您想在属性名下创建一个对象,请执行以下操作

$obj = new stdClass();
$obj->prop = array(1,2,'a');
$newObject = new stdClass();
$newObject->objname = $obj;

print_r(json_encode($newObject));
变成:
{'objname':{'prop':[1,2,'a']}}


祝您有愉快的一天:-)

使用json编码(数组(“长方体”=>数组(“高度”=>10,“宽度”=>20,“深度”=>5))
您的代码堆栈可能存在重复?
$json = json_encode(array(get_class($object) => $object));
$obj = new stdClass();
$obj->prop = array(1,2,'a');
$newObject = new stdClass();
$newObject->objname = $obj;

print_r(json_encode($newObject));