This is what I have:
function get_create
returns a link with new filtered/sorted properties:
function get_create ($new_query = array(), $script = null, $ext = true, $amp = true) {
$pr_url = $GLOBALS['pref_url'].$GLOBALS['host_name'];
$arr_query = array();
if (!empty($new_query)):
$new_query = array_filter($new_query, function($element) {
return !empty($element);}); //delete empty elements
if ($ext) {
$cur_url = str_replace("&", "&",$GLOBALS['cur_url'])
$str_query = parse_url($cur_url, PHP_URL_QUERY); // get string of queries
parse_str($str_query,$arr_query); // create an array with queries
$arr_query = array_replace_recursive($arr_query,$new_query)
$arr_query = get_sort_by_key($arr_query);
}
else {
$arr_query = $new_query; // if $new_query empty
}
//make a new link with new parameters
$fn_query = (!empty($arr_query) ? '?'.http_build_query($arr_query,'',($amp ? '&' : '')) : null);
$fn_script = (!empty($script) ? $script : $GLOBALS['script_name']);
return $pr_url.$fn_script.$fn_query; // return the link
else :
return $GLOBALS['home_url'];
endif;
} // end func
In parameters we have:
$new_query
(which contains the new properties for$_get
part)$script
(contain a new way to script, where data)$ext
(boolean given parameter which make the logic different)$amp
(if true then formats and again)
function get_sort_by_key
helps with sorting array (the keys in array must be in this order: lng-topic-page-sort-search).
function get_sort_by_key($array = array()) {
$new_array = array();
foreach ($array as $key => $value) {
$key = strtolower(trim($key));
switch ($key) {
case $key == 'lng': $order = 0;
break;
case $key == 'topic': $order = 1;
break;
case $key == 'page': $order = 2;
break;
case $key == 'sort': $order = 3;
break;
case $key == 'search': $order = 4;
break;
default: $order = 5; break;
}
$new_array[$order][$key] = $value;
}
ksort($new_array);
return $fn_array = call_user_func_array('array_merge',$new_array);
}
I need to create the function which gets an array full of new parameters and adds or replaces the current $_GET
by them in a specific order.
An example:
I had the URL like this: http://localhost/test.php
. After initialization func: get_create(array('sort' => 1, 'topic' => 2)
I get http://localhost/test.php?topic=2&sort=1
, where the order is important (not http://localhost/test.php?sort=1&topic=2
).
How can I make the function look better? My code works, at least now. But I know that I'm wrong. Maybe some elegant solution exists in my case.