PHP - generating JSON output
$showcaseObject = new stdClass(); $generalObject = new stdClass(); $generalObject->roundCorner = 0; $generalObject->borderStroke = 2; $generalObject->backgroundColor = '#ff开发者_JAVA技巧f'; $showcaseObject->general = $generalObject; echo json_encode($showcaseObject);
and i get something like this
{"general":{
"roundCorner":"0",
"borderStroke":"2",
"backgroundColor":"#ffffff"
}
}
Now i want to get something like this
{"general":{
"round-corner":"0",
"border-stroke":"2",
"background-color":"#ffffff"
}
}
i try to change above code like under code, and get syntax error, unexpected '='
$generalObject->round-corner = $row->general_round_corner_radius;
$generalObject->border-stroke = $row->general_border_stroke;
$generalObject->background-color = $row->background_color;
Help me !
You could use the brace syntax when defining the object members:
$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);
This brace syntax allows you to use expressions rather than just identifiers.
To convert first form to second, traverse over each key and convert the keyname.
foreach ($generalObject as $keyName => $keyValue) { $newKey = strtolower(preg_replace('/([^A-Z])([A-Z])/', "$1_$2", $keyName)); $generalObject[$newKey] = $keyValue; unset($generalObject[$keyName]); }
To access them (this is what you're having a problem with), use bracket notation:
$generalObject['hyphenated-name']
I think the easiest way may be to simply do some string replacement on the JSON strings that you have, to get the hyphen characters in where they couldn't be automatically inserted due to php's allow variable charset:
$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;
精彩评论