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 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端