I'm working on a function that should parse an url to create an associative array.
I'm having trouble replacing numeric keys with their proper string equivalent.
For instance, http://localhost/fr/user/edit/5/?foo=bar&love=hate
produces
Array
(
[langue] => fr
[app] => user
[action] => edit
[id] => 5
[0] => user
[1] => 5
[foo] => bar
[love] => hate
)
what i would like is:
Array
(
[langue] => fr
[app] => user
[action] => edit
[id] => 5
[foo] => bar
[love] => hate
)
Here is my function so far:
<?php
$url = parse_url($_SERVER['REQUEST_URI']);
print_r($url);
// 1./ "folder path" into array
$values = explode('/', $url['path']);
unset($values[0]);
// 2./ "url variables" into array
parse_str($url['query'], $vars);
$url = array_merge($values,$vars);
// 3./ remove empty values
$url = array_filter($url);
print_r($url);
// 4./ replace numeric keys by the application vars
$keys = array('langue','app','action','id');
$count = 0;
foreach($url as $key => $value)
{
if(!is_string($key))
{
$first_array = array_splice ($url, 0,$count);
$insert_array = [$keys[$key] => $value ];
unset($url[$key]);
$url = array_merge ($first_array, $insert_array, $url);
}
$count++;
}
print_r($url);
Seems like you are trying to remove numeric keys.. So do like this
<?php
$arr=Array
(
'langue' => 'fr',
'app' => 'user',
'action' => 'edit',
'id' => '5',
0 => 'user',
1 => '5',
'foo' => 'bar',
'love' => 'hate'
);
$arrNew = array();
foreach($arr as $k=>$v)
{
if(is_numeric($k))
{
unset($arr[$k]);
}
}
print_r($arr);
OUTPUT:
Array
(
[langue] => fr
[app] => user
[action] => edit
[id] => 5
[foo] => bar
[love] => hate
)
EDIT :
Since unset()
didn't work for you. Try this approach.
$arrNew = array(); //We have a new array
foreach($arr as $k=>$v)
{
if(!is_numeric($k))
{
$arrNew[$k]=$v;//Pushing the things to new array.
}
}
unset($arr); //Deleting the old array to save resources
print_r($arrNew);//Printing the new array [The Output will be same as above]
If you want to remove the numeric keys from array.you can try this code :
foreach($arr as $key => $value)
{
if(is_int($key))
{
unset($arr[$key]);
}
}
print_r($arr);
I found a simpler way to do it, tipped by +shankar-damodaran idea to use another array.
<?php
function route($url = NULL){
if(!$url){
$url= $_SERVER['REQUEST_URI'];
}
$url = parse_url($url);
// 1./ "folder path" into array
$values = explode('/', $url['path']);
unset($values[0]);
// 2./ "url variables" into array
parse_str($url['query'], $vars);
$url = array_merge($values,$vars);
// 3./ remove empty values
$url = array_filter($url);
// 4./ replace numeric keys by the application vars
$keys = array('langue','app','action','id');
$url2 = [];
foreach($url as $key => $value)
{
if(!is_string($key))
{
// remove
$key = $keys[$key];
}
$url2[$key]= $value;
}
return $url2;
}
// Example use
$route = route();
print_r($route);