$showcaseObject = new stdClass(); $generalObject = new stdClass(); $generalObject->roundCorner = 0; $generalObject->borderStroke = 2; $generalObject->backgroundColor = '#fff'; $showcaseObject->general = $generalObject; echo json_encode($showcaseObject);
我得到类似的东西
{"general":{
"roundCorner":"0",
"borderStroke":"2",
"backgroundColor":"#ffffff"
}
}
现在我想得到这样的东西
{"general":{
"round-corner":"0",
"border-stroke":"2",
"background-color":"#ffffff"
}
}
我尝试在代码下更改上面的代码,并获得语法错误,意外的'='
$generalObject->round-corner = $row->general_round_corner_radius;
$generalObject->border-stroke = $row->general_border_stroke;
$generalObject->background-color = $row->background_color;
帮助我!
答案 0 :(得分:1)
定义对象成员时可以使用大括号语法:
$showcaseObject = new stdClass();
$generalObject = new stdClass();
$generalObject->{'round-corner'} = 0;
$generalObject->{'border-stroke'} = 2;
$generalObject->{'background-color'} = '#fff';
$showcaseObject->general = $generalObject;
echo json_encode($showcaseObject);
此大括号语法允许您使用表达式而不仅仅是标识符。
答案 1 :(得分:0)
要将第一个表单转换为第二个表单,请遍历每个键并转换键名。
foreach ($generalObject as $keyName => $keyValue) { $newKey = strtolower(preg_replace('/([^A-Z])([A-Z])/', "$1_$2", $keyName)); $generalObject[$newKey] = $keyValue; unset($generalObject[$keyName]); }
要访问它们(这是您遇到的问题),请使用括号表示法:
$generalObject['hyphenated-name']
答案 2 :(得分:0)
我认为最简单的方法可能是简单地在你拥有的JSON字符串上进行一些字符串替换,以便在由于php允许变量字符集而无法自动插入的情况下获取连字符:
$showcaseObject = new stdClass();
$generalObject = new stdClass();
$generalObject->roundCorner = 0;
$generalObject->borderStroke = 2;
$generalObject->backgroundColor = '#fff';
$showcaseObject->general = $generalObject;
$jsonStr = json_encode($showcaseObject);
$jsonStr = str_replace('"roundCorner":', '"round-corner":', $jsonStr);
$jsonStr = str_replace('"borderStroke":', '"border-stroke":', $jsonStr);
$jsonStr = str_replace('"backgroundColor":', '"background-color":', $jsonStr);
echo $jsonStr;