简体   繁体   English

PHP - 获取URL参数并重新排列数组

[英]PHP - Get URL Parameters and Rearrange In Array

The URL coming to the page looks something like this: 进入页面的URL看起来像这样:

"http://localhost/testSite/id/1/friend_id/32/msg_id/5/category_id/40" 的 “http://本地主机/测试网站/ ID / 1 / friend_id / 32 / MSG_ID / 5 / CATEGORY_ID / 40”

I would like to strip these variables ( id/1 , friend_id/32 , msg_id/5 etc.) and make them into an array like this: 我想剥离这些变量( id / 1friend_id / 32msg_id / 5等)并将它们变成这样的数组:

$params = array('id' => 1, 'friend_id' => 32, 'msg_id' => 5, 'category_id' => 40)

So that I can access these values like this: 这样我就可以像这样访问这些值:

$params['id']; $params['friend_id'];

I thought I was getting somewhere with the following code, but it isn't much help. 我以为我正在使用以下代码,但它没有多大帮助。

    $keys = explode('/', $url);
    $k2 = $keys;
    $result = array();

    foreach ($keys as $k => $v) {
       $result[$v] = next($k2); 
    }
    array_pop($result);
    print_r($result);

I would get the following output from the code above: 我会从上面的代码中得到以下输出:

Array
(
    [id] => 1
    [1] => friend_id
    [friend_id] => 32
    [32] => msg_id
    [msg_id] => 5
    [5] => category_id
    [category_id] => 40
)

Has anyone done this previously? 有没有人以前做过这个? How can I modify the code above to make it work properly? 如何修改上面的代码以使其正常工作? Or does anyone have some other ideas on how to do this? 或者有没有人对如何做到这一点有其他想法?

I would really appreciate any help, Thanks! 我真的很感激任何帮助,谢谢!

If this is done by a framework there should be way to get the parameters. 如果这是由框架完成的,那么应该有办法获取参数。 See the doc in that case. 在这种情况下查看文档。

Otherwise you can use simple regex to parse it. 否则,您可以使用简单的正则表达式来解析它。 The idea is to use define a prefix ( $root in the code). 我们的想法是使用define前缀(代码中的$root )。

$url = 'http://localhost/testSite/id/1/friend_id/32/msg_id/5/category_id/40';
$root = 'http://localhost/testSite/';
$params =  substr($url, strlen($root));
preg_match_all("#([^/]+)/([^/]+)#", $params, $match);
$result = array_combine($match[1], $match[2]);
$parts = explode('/', $url);
$len = count($parts);
$result = array();
for ($i = 0; $i < $len; $i+=2) {
  $result[$parts[$i]] = $parts[$i+1];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM