douhuan1979 2014-09-19 21:30 采纳率: 100%
浏览 280

如何将URL拆分为键值对

I am looking to breaking up a URL to key value pair in PHP for example

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

Result would be something like this

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

Current solution:

$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++;
    }
}
  • 写回答

1条回答 默认 最新

  • doushansu9012 2014-09-19 21:37
    关注

    As I mentioned in the comments - $_GET['q'] does not exist because you don't have any query strings on that URL. Try this:

    $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++;
    }
    

    The resulting array is $results. Note that this will only work properly if you have an even number of URI segments.

    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能