我希望在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++;
}
}
答案 0 :(得分:2)
正如我在评论中提到的那样,$_GET['q']
不存在,因为您在该网址上没有任何查询字符串。试试这个:
$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段时,这才能正常工作。