douye2020
2019-04-18 09:18
浏览 112
已采纳

从url到数组的PHP $ _GET值(自定义函数)

Lets say I have an:

$url = "bla.php?test1=a&test2=b&test1=c&test2=d&test1=e&test2=f&test1=g&test2=h&test1=i&test2=j";

then I wish to run the custom function getToArray("test1") which would create an array with values ["a", "c", "e", "g", "i"]

I am trying to figure out how, but so far no luck.

Please note that in case of using getToArray("test2"), the last value from $_GET will be "j" which is end of the string...

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douhuang3740 2019-04-18 09:25
    已采纳

    This should do what you want. Basically it keeps exploding the url, first by ? to get the query string, then that by & to get the individual key/value pairs, and then each of those pairs by = to get the key and value. If the key matches the search string, it is added to the output array.

    function getToArray($url, $key) {
        $values = array();
        list (, $query_string) = explode('?', $url, 2);
        foreach (explode('&', $query_string) as $param) {
            list($k, $v) = explode('=', $param, 2);
            if ($k == $key) $values[] = $v;
        }
        return $values;
    }
    print_r(getToArray($url, 'test1'));
    print_r(getToArray($url, 'test2'));
    

    Output:

    Array ( [0] => a [1] => c [2] => e [3] => g [4] => i ) 
    Array ( [0] => b [1] => d [2] => f [3] => h [4] => j )
    

    Demo on 3v4l.org

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • duanji9378 2019-04-18 09:48

    You can first remove first segments from url.

    Then explode by & and then =

    function getToArray($url, $key)
    {
        $arr  = explode("&", $url);
        $temp = [];
        array_walk($arr, function ($item, $key) use (&$temp) {
            $d             = explode('=', $item);
            $temp[$d[0]][] = $d[1];
        });
        return $temp[$key];
    }
    $url  = str_replace('bla.php?', '', "bla.php?test1=a&test2=b&test1=c&test2=d&test1=e&test2=f&test1=g&test2=h&test1=i&test2=j");
    $result = getToArray($url, 'test1');
    print_r($result);
    

    Demo

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题