Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

php json decode with variables that contains dashes

{"general":{
 "round-corner":"0",
 "border-stroke":"2",
 "background-color":"#ffffff"
 }
}

I have this json string, I know that php variable names doesn't support dashes. So what to do in this case ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When dealing with valid json you don't need to do anything special to use the result in php as long as you don't use extract().

Admiditly it looks cleaner to let json_decode return an array here as Jay Bhatt suggests but you are also free to use a normal object as return (which is an instance of stdclass).

The properties of the returned object can be nearly anything. You just need to use the property name as a php-string instead of a hardcoded literal.

$obj->{'a sentence with spaces and umlauts ?ü? is valid here'}

<?php

$json = <<<JSON
{"general":{
 "round-corner":"0",
 "border-stroke":"2",
 "background-color ?ü??$%§":"#ffffff"
 }
}
JSON;

$obj = json_decode($json);

$keyName = "round-corner";
var_dump($obj->general->{'round-corner'});
var_dump($obj->general->$keyName);
var_dump($obj->general->{'background-color ?ü??$%§'});

Result


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...