2015-05-13 71 views
0

JSON我通过Ajax发送查询字符串格式化的文本像波纹管PHP脚本:转换查询字符串在PHP

title=hello&custLength=200&custWidth=300 

而且我想这个文本JSON对象通过这个结果在PHP转换:

{ 
    "title" : "hello", 
    "custLength" : 200, 
    "custWidth" : 300 
} 

我怎样才能做到这一点。有没有人有办法解决吗?

编辑: 事实上,我必须以形成三个元件由标题custLengthcustWidth名称和我试图经由的serialize() jquery的方法来发送这些元素作为一个参数到PHP脚本。

这个代码是用于发送数据到PHP:

customizingOptions = $('#title,#custLength,#custWidth').serialize(); 

$.post('cardOperations',{action:'add','p_id':p_id,'quantity':quantity,'customizingOptions':customizingOptions},function(data){ 

if (data.success){ 

    goBackBtn('show'); 

    updateTopCard('new');   
}     

},'json'); 

在PHP脚本我用json_encode()的转换只customizingOptions参数为JSON。
但结果不是我所期望的和结果是一个简单的文字是这样的:

"title=hello&custLength=200&custWidth=300" 
+0

哪一部分是它是你坚持?读取查询字符串或写入JSON? – JJJ

+0

echo json_encode($ _ GET);试试这个 – Codelord

+0

我已经添加了更多的细节问题。 –

回答

6
$check = "title=hello&custLength=200&custWidth=300"; 
$keywords = preg_split("/[\s,=,&]+/", $check); 
$arr=array(); 
for($i=0;$i<sizeof($keywords);$i++) 
{ 
$arr[$keywords[$i]] = $keywords[++$i]; 
} 
$obj =(object)$arr; 
echo json_encode($obj); 

尝试这个代码,您得到您想要的结果

+1

是的。它完美地工作。 –

1

最简单的如何从$_GET字符串achiev JSON对象的方法是非常简单的:

json_encode($_GET) 

这将产生以下JSON输出:

{"title":"hello","custLength":"200","custWidth":"300"} 

或者你可以使用一些解析函数作为第一(例如 - 保存所有variab将其转换为数组),然后您可以将解析的输出发送到json_encode()函数。

不指定详细的需求,也有许多解决方案。

+0

感谢您的回复。但我想只编码Get Request的一个参数,它包含一个queryString格式的文本。我添加了更多的细节来提问。我再次感谢你看到 –