目前,我正在努力让我的网址缩短脚本能够从Google Analytics跟踪UTM变量。我还想提供我自己的(campaign / keyword / source / etc ...)变量。
我正在尝试筛选$ _GET,选择“已批准”的键/值对,并设置每个键的条件是UTM变量优先级更高(我只想在数据库中存储一个值)。
我的代码目前是:
//Parse $_GET and only get the key/pairs that we need and store them in global $url_params for use through out the script
function set_url_params($allowed=NULL) { // $allowed is arg to add new values in future dev
global $url_params;
$allowed = array(
'l', // Redirect key (e.g http://example.com?l=a1dFd7)
'utm_campaign',
'campaign',
'utm_source' ,
'source',
'utm_medium',
'medium',
'utm_term',
'term',
'keyword',
'kw',
);
$approved = array_intersect_key($_GET, array_flip($allowed));
foreach($approved as $key => $value) {
strip_tags(urldecode(trim($value)));
$url_params[$key] = $value;
}
//Assign variables to global $url_params variable so other functions can use them.
//NOTE: Google Analytics UTM parameters take precedence over script values.
$url_params['l'] = isset($approved['l']) ? $approved['l'] : NULL ;
$url_params['campaign'] = isset($approved['utm_campaign']) ? $approved['utm_campaign'] : $approved['campaign'];
$url_params['source'] = isset($approved['utm_source']) ? $approved['utm_source'] : $approved['source'];
$url_params['medium'] = isset($approved['utm_medium']) ? $approved['utm_medium'] : $approved['medium'];
$url_params['term'] = isset($approved['utm_term']) ? $approved['utm_term'] : $approved['term'];
$url_params['keyword'] = isset($approved['keyword']) ? $approved['keyword'] : $approved['kw'];
// Just in case $url_params doesn't have a 'keyword' set, we will use 'term' instead.
$url_params['keyword'] = isset($url_params['keyword']) ? $url_params['keyword'] : $url_params['term'];
}
我基本上想要在没有所有isset()的情况下找到更简洁的方法。对于我想要取消设置的未定义变量,我也会收到NOTICE错误(在E_ALL中运行),所以我没有得到这些错误。
答案 0 :(得分:0)
可能与此有关吗?
$params = array(
'l' => array('default' => null),
'campaign' => array('default' => null, 'alt' => 'utm_campaign'),
...
);
$url_params = array();
foreach ($params as $key => $info) {
$url_params[$key] = $info['default'];
if (isset($info['alt'], $_GET[$info['alt']])) {
$url_params[$key] = $_GET[$info['alt']];
}
if (isset($_GET[$key]) {
$url_params[$key] = $_GET[$key];
}
}