Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

convert query String to json in php

I send a QueryString formatted text like bellow to a php Script via Ajax:

title=hello&custLength=200&custWidth=300  

And I want to convert this text to a JSON Object by this result in PHP:

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

How can i do that. Does anyone have a solution?

Edit : In fact i have three element in a form by title , custLength and custWidth names and i tried to send these elements via serialize() jquery method as one parameter to PHP script.

this code is for Send data to 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');

in PHP script i used json_encode() for convert only customizingOptions parameter to a json.
But the result was not what I expected and result was a simple Text like this:

"title=hello&custLength=200&custWidth=300"
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)
$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);

Try This code You Get Your Desired Result


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...