Lisa8
Lisa8

Reputation: 179

PHP JSON pass as query string

I have few status return into json_encode object based on certain circumstances.

if(verify == 1)
    $data = array('status'=>'SUCCESS', 'points'=>$points, 'user'=>$user);

if(verify == 2)
    $data = array('status'=>'INACTIVE');

if(verify == 0)
    $data = array('status'=>'FAILED');

$data_str = json_encode($data);

I need $data_str to add as query string, when it redirect to hitter URL, such as: https://www.example.com/members?status=SUCCESS&points=2500&[email protected] OR https://www.example.com/members?status=INACTIVE

How could $data_str to be pass as query string?

Upvotes: 0

Views: 1908

Answers (3)

Ali
Ali

Reputation: 1438

You can use the PHP function http_build_query to achieve this and you never need to use anything else like foreach loop:

if($verify == 1)
    $data = array('status'=>'SUCCESS', 'points'=>$points, 'user'=>$user);

if($verify == 2)
    $data = array('status'=>'INACTIVE');

if($verify == 0)
    $data = array('status'=>'FAILED');

$url = https://www.example.com/members?.http_build_query($data);

EDIT

Here is demo

Upvotes: 3

Murad Hasan
Murad Hasan

Reputation: 9583

Try this:

$verify = 1;
$points = 2500;
$user = 'albert';

if($verify == 1)
    $data = array('status'=>'SUCCESS', 'points'=>$points, 'user'=>$user);

if($verify == 2)
    $data = array('status'=>'INACTIVE');

if($verify == 0)
    $data = array('status'=>'FAILED');

//$data_str = json_encode($data);

$qryStr = array();
foreach($data as  $key => $val){
    $qryStr[] = $key."=".$val;
}
echo $url = 'https://www.example.com/'.implode("&", $qryStr); //https://www.example.com/status=SUCCESS&points=2500&user=albert

OR use http_build_query().

echo $url = 'https://www.example.com/'.http_build_query($data); //https://www.example.com/status=SUCCESS&points=2500&user=albert

Upvotes: 0

2Fwebd
2Fwebd

Reputation: 2095

Another option would be :

  1. Turn your array into a string using : implode

  2. Make it ready for an URL using : urlencode

Hope that helps,

Upvotes: 0

Related Questions