与php

时间:2017-01-17 18:58:46

标签: php json

我有以下代码。任何人都可以向我解释这些代码,我没有得到所有这些。 这是代码

$query = $_SERVER['QUERY_STRING'];
$query  = explode('&', $_SERVER['QUERY_STRING']);enter code here
$params = array();
foreach ($query as $param) {
list($name, $value) = explode('=', $param, 2);
$params[urldecode($name)][] = urldecode($value);
}
//echo jsonEncode($params);
$categories = implode(", ", $params['categories']);
$types = implode(", ", $params['type']);

我对这两个变量感到困惑" $ param" &安培; " $ PARAMS"

1 个答案:

答案 0 :(得分:0)

如果通过任何查询字符串访问页面,$_SERVER['QUERY_STRING']将获取该查询字符串。

例如,如果您在浏览器中调用url

http://65enginespart.com/

然后$_SERVER['QUERY_STRING']包含以下数据

"name=msk&job=developer"

explode()用于将字符串转换为数组,其中delimeter是&

$query = explode('&', $_SERVER['QUERY_STRING']);

现在$query包含包含以下数据的数组

Array
    (
        [0] => "name=msk"
        [1] => job=developer"
    )   

$params = array();  //created to hold $_SERVER['QUERY_STRING'] array of strings


foreach ($query as $param) {
    list($name, $value) = explode('=', $param, 2);      
    //above line try to convert "name=msk" into array like this ["name"] => array([0] = msk)
    //list() function is used to assign values to a list of variables in one operation.
    $params[urldecode($name)][] = urldecode($value);
}

$params包含以下数组数据

(
    ["name] => Array
        (
            [0] => msk
        )
    [job] => Array
        (
            [0] => developer"
        )
)


echo json_encode($params);

json_encode()用于将php数组转换为JSON

{"\"name":["msk"],"job":["developer\""]}

并提出疑问

$param只是一个循环迭代器
$params是用于保存$_SERVER['QUERY_STRING']数据的数组