0

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&user=albert@hotmail.com OR https://www.example.com/members?status=INACTIVE

How could $data_str to be pass as query string?

2
  • You can use a foreach loop to loop through key-value pairs of $data and construct your query string. Don't forget to set rawurlencode for the value part.
    – Timothy Ha
    May 16, 2016 at 9:51
  • use http_build_query() function
    – splash58
    May 16, 2016 at 9:55

3 Answers 3

3

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

0
0

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,

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.