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&[email protected] 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. Commented May 16, 2016 at 9:51
  • use http_build_query() function Commented 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

Sign up to request clarification or add additional context in comments.

Comments

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,

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.