php:用关联键替换数字id

时间:2013-12-05 11:44:58

标签: php url-parsing

我正在研究一个应该解析url的函数来创建一个关联数组。

我在使用正确的字符串等效替换数字键时遇到了问题。

例如,http://localhost/fr/user/edit/5/?foo=bar&love=hate生成

Array
(
    [langue] => fr
    [app] => user
    [action] => edit
    [id] => 5
    [0] => user
    [1] => 5
    [foo] => bar
    [love] => hate
)

我想要的是:

Array
(
    [langue] => fr
    [app] => user
    [action] => edit
    [id] => 5
    [foo] => bar
    [love] => hate
)

到目前为止,这是我的功能:

<?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);

3 个答案:

答案 0 :(得分:1)

好像你正试图删除数字键..所以这样做

<?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);

<强>输出:

Array
(
    [langue] => fr
    [app] => user
    [action] => edit
    [id] => 5
    [foo] => bar
    [love] => hate
)

编辑:

由于 unset() 不适合您。尝试这种方法。

$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]

答案 1 :(得分:0)

如果要从数组中删除数字键,可以尝试以下代码:

foreach($arr as $key => $value)
{
    if(is_int($key))
    {
        unset($arr[$key]);
    }
}
print_r($arr);

答案 2 :(得分:0)

我找到了一种更简单的方法,用+ shankar-damodaran的想法来使用另一个阵列。

<?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);