How to pass an array within a query string?

前端 未结 10 1347
一整个雨季
一整个雨季 2020-11-22 02:35

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.

相关标签:
10条回答
  • 2020-11-22 02:58

    Check the parse_string function 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
    $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
    
    ?>
    
    0 讨论(0)
  • 2020-11-22 03:02

    You can use http_build_query to 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_query method, 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.

    0 讨论(0)
  • 2020-11-22 03:06

    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:

    let data = {
      str: 'abc',
      arr: ['abc', 123]
    }
    
    new URLSearchParams(data).toString();  // ?str=abc&arr=abc,123
    
    0 讨论(0)
  • I use React and Rails. I did:

    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
    
    0 讨论(0)
提交回复
热议问题