PHP JSON 作为查询字符串传递

PHP JSON pass as query string

根据某些情况,我对 json_encode 对象的状态 return 很少。

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);

我需要 $data_str 添加为查询字符串,当它重定向到 hitter URL 时,例如:https://www.example.com/members?status=SUCCESS&points=2500&user=albert@hotmail.comhttps://www.example.com/members?status=INACTIVE

如何将 $data_str 作为查询字符串传递?

您可以使用 PHP 函数 http_build_query 来实现这一点,您永远不需要使用任何其他东西,例如 foreach 循环:

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);

编辑

这里是demo

另一种选择是:

  1. 使用以下方法将数组转换为字符串: implode

  2. 使用 urlencode

  3. 为 URL 做好准备

希望对您有所帮助,

试试这个:

$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

或使用 http_build_query().

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