如何将URL分解为键值对


How to breakup URL to keyvalue pair

我想在PHP中分解URL到键值对例如

/name/foo/location/bar/account/3449

结果将类似于

array(name => "foo", location => "bar", account => "3449");

当前解决方案:

$urlPieces = explode('/', $_GET['q']);
$results = array();
$count = 0;
$keyName = "";
foreach ($urlPieces as $key=>$value) {
    if($count % 2 != 0){
       $results[$keyName] = $urlPieces[$count++];
    }else{
       $keyName = $value;
       $count++;
    }
}

正如我在评论中提到的,$_GET['q']不存在,因为您在该URL上没有任何查询字符串。试试这个:

$url = strtok($_SERVER["REQUEST_URI"],'?'); //get the URL and remove query strings
$urlPieces = explode('/', $url); //create array from that URL
$count = 0;
$results = array();
foreach ($urlPieces as $key=>$value) { 
    if($count % 2 != 0){
       $results[$urlPieces[$key]] = $urlPieces[$count+1]; 
        //new array key is the current $key (aka $urlPieces[$key])
        //new array value is the value of the next key (aka $urlPieces[$count+1])
    }
    $count++;
}

得到的数组是$results。请注意,只有当您有偶数个URI段时,这才能正常工作。