php unset url parameters array

时间:2016-04-04 18:23:55

标签: php arrays url

I have a url thats parameters are an array. It looks like this:

&fq[]=subjects:Human+beings&fq[]=subjects:Ethnology

When I wan't to unset a parameter I usually send it through this function:

<a href="<?php echo remove_modify_url(array('fq' => urlencode($facetValue)));?>"><?php echo $facetValue; ?></a>

function remove_modify_url($par, $url = FALSE){
if($url == FALSE){
    $scheme = $_SERVER['SERVER_PORT'] == 80 ? 'http' : 'https';
    $url = $scheme.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}
$url_array = parse_url($url);
if(!empty($url_array['query'])){
    parse_str($url_array['query'], $query_array);
    foreach ($par as $key => $value) {
            unset($query_array[$key]);
    }
}
return $url_array['path'].'?'.http_build_query($query_array);
}

However, this unsets everything that has a key of fq. I'd like to unset a specific array parameter without deleting all of the other parameters. In this case a user clicks on the a button to remove subjects:Human+beings and the url changes to fq[]=subjects:Ethnology.

1 个答案:

答案 0 :(得分:0)

Hopefully I'm following correctly, but I would just use the $_GET array. Either way array_search() can find the one to unset():

$params = $_GET;
$delete = 'subjects:Ethnology';

unset($params['fq'][array_search($delete, $params['fq'])]);    
echo http_build_query($params);

Or preg_grep() to get the ones not matching. Maybe overkill for only one, but more flexible search:

$params['fq'] = preg_grep("/$delete/", $params['fq'], PREG_GREP_INVERT);
echo http_build_query($params);