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

从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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!