问题描述
我以前从未使用过JSON,并且正在尝试利用以下javascript: http://jqueryselectcombo.googlecode.com/files/jquery.selectCombo1.2.6.js
I've never used JSON before and I'm trying to utilize the following javascript:http://jqueryselectcombo.googlecode.com/files/jquery.selectCombo1.2.6.js
它需要以下格式的JSON输出:
It needs a JSON output in the following format:
[{oV: 'myfirstvalue', oT: 'myfirsttext'},
{oV: 'mysecondvalue', oT: 'mysecondtext'}]
您能指导我如何使用PHP生成上述JSON输出的示例吗?
Could you guide me to an example on how to generate a JSON output as above, using PHP?
推荐答案
最简单的方法可能是从所需的对的关联数组开始:
The simplest way would probably be to start with an associative array of the pairs you want:
$data = array("myfirstvalue" => "myfirsttext", "mysecondvalue" => "mysecondtext");
然后使用foreach和一些字符串连接:
then use a foreach and some string concatenation:
$jsontext = "[";
foreach($data as $key => $value) {
$jsontext .= "{oV: '".addslashes($key)."', oT: '".addslashes($value)."'},";
}
$jsontext = substr_replace($jsontext, '', -1); // to get rid of extra comma
$jsontext .= "]";
或者,如果您使用的是最新版本的PHP,则可以使用内置的json编码功能-请注意传递给它们的数据应使其与期望的格式匹配.
Or if you have a recent version of PHP, you can use the json encoding functions built in - just be careful what data you pass them to make it match the expected format.
这篇关于如何使用php生成json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!