简体   繁体   English

如何从 url 中获取多个具有相同名称的值?

[英]How do I $GET multiple values with the same name from a url?

I have created a form using checkboxes with the method set to GET.我使用复选框创建了一个表单,方法设置为 GET。

The results are example.com/careers/?career_type=val1&career_type=val2结果是example.com/careers/?career_type=val1&career_type=val2

<?= $_GET['career_type']; ?>

This only displays val2.这仅显示 val2。

Is it possible to display both values?是否可以显示两个值?

While it's perfectly valid to have multiple parameters with the same name, PHP doesn't handle it very well.虽然拥有多个具有相同名称的参数是完全有效的,但 PHP 并不能很好地处理它。 You have two options.你有两个选择。

  1. Change the URL to use an array eg example.com/careers/?career_type[]=va1&career_type[]=val2 .将 URL 更改为使用数组,例如example.com/careers/?career_type[]=va1&career_type[]=val2 Then $_GET['career_type'] will be returned as an array containing val1 and val2.然后$_GET['career_type']将作为包含 val1 和 val2 的数组返回。 If you're using a form to generate this URL, you can simply name your fields name="career_type[]"如果您使用表单生成此 URL,您只需将字段name="career_type[]"

  2. If that's not possible, you can manually parse the query string.如果这不可能,您可以手动解析查询字符串。 This will have the same effect:这将产生相同的效果:

    $query = explode('&', $_SERVER['QUERY_STRING']);
    $params = [];
    foreach ($query as $param) {
        [$name, $value] = explode('=', $param, 2);
        $params[urldecode($name)][] = urldecode($value);
    }

    var_dump($params['career_type']);

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

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