php 如何在查询字符串中传递数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6243051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:45:28  来源:igfitidea点击:

How to pass an array within a query string?

phparraysquery-stringquerystringparameter

提问by Yarin

Is there a standard way of passing an array through a query string?

是否有通过查询字符串传递数组的标准方法?

To be clear, I have a query string with multiple values, one of which would be an array value. I want that query string value to be treated as an array- I don't want the array to be exploded so that it is indistinguishable from the other query string variables.

需要明确的是,我有一个包含多个值的查询字符串,其中一个是数组值。我希望该查询字符串值被视为一个数组 - 我不希望该数组被分解,以便它与其他查询字符串变量无法区分。

Also, according to this post answer, the author suggests that query string support for arrays is not defined. Is this accurate?

此外,根据这篇帖子的回答,作者建议未定义对数组的查询字符串支持。这是准确的吗?

EDIT:

编辑:

Based on @Alex's answer, there is no standard way of doing this, so my follow up is then what is an easy way to recognizethat the paramater I'm reading is an array in both PHPand Javascript?

根据@Alex 的回答,没有标准的方法可以做到这一点,所以我的后续工作是识别我正在阅读的参数是PHPJavascript 中的数组的简单方法是什么?

Would it be acceptable to name multiple params the same name, and that way I would know that they belong to an array? Example:

将多个参数命名为相同的名称是否可以接受,这样我就知道它们属于一个数组?例子:

?myarray=value1&myarray=value2&myarray=value3...

Or would this be bad practice?

或者这会是不好的做法吗?

回答by Yarin

Here's what I figured out:

这是我想出的:

Submitting multi-value form fields, i.e. submitting arrays through GET/POST vars, can be done several different ways, as a standard is not necessarily spelled out.

提交多值表单字段,即通过 GET/POST 变量提交数组,可以通过几种不同的方式来完成,因为不一定要详细说明标准。

Three possible ways to send multi-value fields or arrays would be:

发送多值字段或数组的三种可能方法是:

  • ?cars[]=Saab&cars[]=Audi(Best way- PHP reads this into an array)
  • ?cars=Saab&cars=Audi(Bad way- PHP will only register last value)
  • ?cars=Saab,Audi(Haven't tried this)
  • ?cars[]=Saab&cars[]=Audi(最好的方法-PHP 将其读入数组)
  • ?cars=Saab&cars=Audi(糟糕的方式 - PHP 只会注册最后一个值)
  • ?cars=Saab,Audi(这个没试过)

Form Examples

表单示例

On a form, multi-valued fields could take the form of a select box set to multiple:

在表单上,​​多值字段可以采用设置为 multiple选择框的形式:

<form> 
    <select multiple="multiple" name="cars[]"> 
        <option>Volvo</option> 
        <option>Saab</option> 
        <option>Mercedes</option> 
    </select>
</form>

(NOTE: In this case, it would be important to name the select control some_name[], so that the resulting request vars would be registered as an array by PHP)

(注意:在这种情况下,命名选择控件很重要some_name[],这样生成的请求变量将被 PHP 注册为数组)

... or as multiple hidden fields with the same name:

...或作为多个具有相同名称的隐藏字段

<input type="hidden" name="cars[]" value="Volvo">
<input type="hidden" name="cars[]" value="Saab">
<input type="hidden" name="cars[]" value="Mercedes">


NOTE:Using field[]for multiple values is really poorly documented. I don't see any mention of it in the section on multi-valued keys in Query string - Wikipedia, or in the W3C docsdealing with multi-select inputs.

注:使用field[]多个值实在是记录不完整。在Query string - Wikipedia 中的多值键部分或处理多选输入的W3C 文档中,我没有看到任何提及。



UPDATE

更新

As commenters have pointed out, this is very much framework-specific. Some examples:

正如评论者所指出的,这是非常特定于框架的。一些例子:

Query string:

请求参数:

?list_a=1&list_a=2&list_a=3&list_b[]=1&list_b[]=2&list_b[]=3&list_c=1,2,3

Rails:

导轨:

"list_a": "3", 
"list_b":[
    "1",
    "2",
    "3"
  ], 
"list_c": "1,2,3"

Angular:

角度:

 "list_a": [
    "1",
    "2",
    "3"
  ],
  "list_b[]": [
    "1",
    "2",
    "3"
  ],
  "list_c": "1,2,3"

(Angular discussion)

(角度讨论

See comments for examples in node.js, Wordpress, ASP.net

有关node.jsWordpressASP.net 中的示例,请参阅注释



Maintaining order:One more thing to consider is that if you need to maintain the orderof your items (i.e. array as an ordered list), you really only have one option, which is passing a delimited list of values, and explicitly converting it to an array yourself.

维护顺序:还要考虑的另一件事是,如果您需要维护项目的顺序(即数组作为有序列表),您实际上只有一个选项,即传递一个分隔的值列表,并将其显式转换为自己一个数组。

回答by Alex K.

A query string carries textual data so there is no option but to explode the array, encode it correctly and pass it in a representational format of your choice:

查询字符串携带文本数据,因此别无选择,只能分解数组,正确编码并以您选择的表示格式传递它:

p1=value1&pN=valueN...
data=[value1,...,valueN]
data={p1:value1,...,pN:valueN}

p1=value1&pN=valueN...
data=[value1,...,valueN]
data={p1:value1,...,pN:valueN}

and then decode it in your server side code.

然后在您的服务器端代码中对其进行解码。

回答by Berry Tsakala

I don't think there's a standard.
Each web environment provides its own 'standard' for such things. Besides, the url is usually too short for anything (256 bytes limit on some browsers). Of course longer arrays/data can be send with POST requests.

我认为没有标准。
每个网络环境都为这些事情提供了自己的“标准”。此外,该 url 通常对于任何内容都太短(某些浏览器限制为 256 字节)。当然,更长的数组/数据可以通过 POST 请求发送。

However, there are some methods:

但是,有一些方法:

  1. There's a PHP way, which uses square brackets ([,]) in URL queries. For example a query such as ?array_name[]=item&array_name[]=item_2has been said to work, despite being poorly documented, with PHP automatically converting it into an array. Source: https://stackoverflow.com/a/9547490/3787376

  2. Object data-interchange formats (e.g. JSON - official website, PHP documentation) can also be used if they have methods of converting variables to and from strings as JSON does.
    Also an url-encoder (available for most programming languages) is required for HTTP get requests to encode the string data correctly.

  1. 有一种 PHP 方式,它在 URL 查询中使用方括号 ( [, ])。例如?array_name[]=item&array_name[]=item_2,尽管文档很差,但据说这样的查询可以工作,PHP 会自动将其转换为数组。来源:https: //stackoverflow.com/a/9547490/3787376

  2. 如果对象数据交换格式(例如 JSON官方网站PHP 文档)具有像 JSON 那样将变量与字符串相互转换的方法,也可以使用它们。
    HTTP get 请求还需要一个 url-encoder(可用于大多数编程语言)以正确编码字符串数据。

Although the "square brackets method" is simple and works, it is limited to PHP and arrays.
If other types of variable such as classes or passing variables within query strings in a language other than PHP is required, the JSON method is recommended.

“方括号法”虽然简单有效,但仅限于PHP和数组。
如果需要其他类型的变量,例如类或使用 PHP 以外的语言在查询字符串中传递变量,则建议使用 JSON 方法。

Example in PHP of JSON method (method 2):

JSON 方法的 PHP 示例(方法 2):

$myarray = array(2, 46, 34, "dfg");
$serialized = json_encode($myarray)
$data = 'myarray=' . rawurlencode($serialized);
// Send to page via cURL, header() or other service.

Code for receiving page (PHP):

接收页面代码(PHP):

$myarray = json_decode($_GET["myarray"]); // Or $_POST["myarray"] if a post request.

回答by vara

I feel it would be helpful for someone who is looking for passing the array in a query string to a servlet. I tested below query string and was able to get the array values using req.getgetParameterValues(); method. Below is the query string I passed through browser.

我觉得这对于正在寻找将查询字符串中的数组传递给 servlet 的人会很有帮助。我在查询字符串下面进行了测试,并且能够使用 req.getgetParameterValues(); 获取数组值。方法。下面是我通过浏览器传递的查询字符串。

  http://localhost:8080/ServletsTutorials/*.html? 
  myname=abc&initial=xyz&checkbox=a&checkbox=b

checkbox is my parameter array here.

复选框是我的参数数组。

回答by Alia

This works for me:

这对我有用:

In link, to attribute has value:

在链接中,to 属性具有值:

to="/filter/arr?fruits=apple&fruits=banana"

Route can handle this:

Route 可以处理这个:

path="/filter/:arr"

For Multiple arrays:

对于多个阵列:

to="filter/arr?fruits=apple&fruits=banana&vegetables=potato&vegetables=onion"

Route stays same.

路线保持不变。

SCREENSHOT

截屏

enter image description here

在此处输入图片说明

回答by Linielson

I use React and Rails. I did:

我使用 React 和 Rails。我做了:

js

js

  let params = {
    filter_array: ['A', 'B', 'C']
  }

  ...

  //transform params in URI

  Object.keys(params).map(key => {
    if (Array.isArray(params[key])) {
      return params[key].map((value) => `${key}[]=${value}`).join('&')
    }
  }
  //filter_array[]=A&filter_array[]=B&filter_array[]=C

回答by DCShannon

You mention PHP and Javascript in your question, but not in the tags. I reached this question with the intention of passing an array to an MVC.Net action.

您在问题中提到了 PHP 和 Javascript,但没有在标签中提到。我提出这个问题的目的是将数组传递给 MVC.Net 操作。

I found the answer to my question here: the expected format is the one you proposed in your question, with multiple parameters having the same name.

我在这里找到了我的问题的答案:预期的格式是您在问题中提出的格式,多个参数具有相同的名称。

回答by keyboardP

You can use http_build_queryto generate a URL-encoded querystring from an array in PHP. Whilst the resulting querystring will be expanded, you can decide on a unique separator you want as a parameter to the http_build_querymethod, so when it comes to decoding, you can check what separator was used. If it was the unique one you chose, then that would be the array querystring otherwise it would be the normal querystrings.

您可以使用http_build_query从 PHP 中的数组生成 URL 编码的查询字符串。虽然结果查询字符串将被扩展,但您可以决定一个唯一的分隔符作为http_build_query方法的参数,因此在解码时,您可以检查使用了哪个分隔符。如果它是您选择的唯一一个,那么它将是数组查询字符串,否则它将是普通的查询字符串。

回答by Jo?o Haas

Although there isn't a standard on the URL part, there is one standard for JavaScript. If you pass objects containing arrays to URLSearchParams, and call toString()on it, it will transform it into a comma separated list of items:

尽管 URL 部分没有标准,但 JavaScript 有一个标准。如果您将包含数组的对象传递给URLSearchParams,并调用toString()它,它会将其转换为逗号分隔的项目列表:

let data = {
  str: 'abc',
  arr: ['abc', 123]
}

new URLSearchParams(data).toString();  # ?str=abc&arr=abc,123

回答by Dan Murfitt

Check the parse_stringfunction http://php.net/manual/en/function.parse-str.php

检查parse_string功能http://php.net/manual/en/function.parse-str.php

It will return all the variables from a query string, including arrays.

它将返回查询字符串中的所有变量,包括数组。

Example from php.net:

来自 php.net 的示例:

<?php
$str?=?"first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo?$first;??//?value
echo?$arr[0];?//?foo?bar
echo?$arr[1];?//?baz

parse_str($str,?$output);
echo?$output['first'];??//?value
echo?$output['arr'][0];?//?foo?bar
echo?$output['arr'][1];?//?baz

?>