METANIT.COM

Php passing array in get

В прошлых темах была рассмотрена отправка на сервер отдельных значений. Однако отправка набора значений, то есть массивов в PHP может вызвать некоторые сложности. Рассмотрим, как можно отправить на сервер и соответственно получить на сервере массивы данных.

Например, определим следующий файл users.php :

 echo "В массиве " . count($users) . " элементa/ов
"; foreach($users as $user) echo "$user
"; ?>

В данном случае мы предполагаем, что параметр «users», который передается в запросе типа GET, будет представлять массив. И соответствено мы сможем получить из него данные.

Чтобы передать массив этому скрипту, обратимся к нему со следующим запросом:

http://localhost/users.php?users[]=Tom&users[]=Bob&users[]=Sam

Чтобы определить параметр строки запроса как массив, после названия параметра указываются квадраные скобки []. Затем мы можем присвоить некоторое значение: users[]=Tom . И сколько раз подобным образом будет присвоено значений, столько значений и будет в массиве. Все значения, как и обычно, отделяются амперсандом. Так, в данном случае в массив передаются три значения.

Передача массивов в PHP на сервер в запросе GET

Подобным образом мы можем отправлять данные в запросе POST из формы. Например, определим следующий скрипт:

     "; foreach($users as $user) echo "$user
"; > ?>

Форма ввода данных

User 1:

User 2:

User 3:

Как известно, название ключа передаваемых на сервер данных соответствует значению атрибута name у элемента формы. И чтобы указать, что какое-то поле ввода будет поставлять значение для массива, у атрибут name поля ввода в качестве значения принимает название массива с квадратными скобками:

Соответственно, сколько полей ввода с одним и тем же именем массива мы укажем, столько значений мы сможем передать на сервер. Так, в данном случае на сервер передается три значения в массиве users:

Отправка массивов на сервер методом POST из формы в PHP

Причем данный принцип применяется и к другим типам полей ввода формы html.

При этом в примерах выше передавался обычный массив, каждый элемент которого в качестве ключа имеет числовой индекс. Соотвенно, используя индекс, мы можем получить определенный элемент массива:

$firstUser = $_POST["users"][0]; echo $firstUser;

Но также мы можем в элементах формы явным образом указать ключи:

     $secondUser
$thirdUser"; > ?>

Форма ввода данных

User 1:

User 2:

User 3:

Например, первое поле добавляет в массив элемент с ключом «first»

Поэтому на сервере мы можем с помощью данного ключа получить соответствующий элемент:

$firstUser = $_POST["users"]["first"];

Источник

How to pass an array via $_GET in php?

You can also specify keys: Multidimentional arrays work too: does this automatically: An alternative would be to pass json encoded arrays: Thanks Solution 1: You can use the syntax to pass arrays through _GET: PHP understands this syntax, so will be equal to .

Читайте также:  text-transform

How to pass an array via $_GET in php?

How can I pass one or more variables of type array to another page via $_GET?

I always passed variable values in the form ?a=1&b=2&c=3

Do I need to write a for loop and append all the values?

You can use the [] syntax to pass arrays through _GET:

PHP understands this syntax, so $_GET[‘a’] will be equal to array(1, 2, 3) .

You can also specify keys:

http_build_query() does this automatically:

http_build_query(array('a' => array(1, 2, 3))) // "a[]=1&a[]=2&a[]=3" http_build_query(array( 'a' => array( 'foo' => 'bar', 'bar' => array(1, 2, 3), ) )); // "a[foo]=bar&a[bar][]=1&a[bar][]=2&a[bar][]=3" 

An alternative would be to pass json encoded arrays:

And you can parse a with json_decode :

$a = json_decode($_GET['a']); // array(1, 2, 3) 

And encode it again with json_encode:

json_encode(array(1, 2, 3)); // "[1,2,3]" 

Dont ever use serialize() for this purpose . Serialize allows to serialize objects, and there is ways to make them execute code. So you should never deserialize untrusted strings.

You can pass an associative array to http_build_query() and append the resulting string as the query string to the URL. The array will automatically be parsed by PHP so $_GET on the receiving page will contain an array.

$query_str = http_build_query(array( 'a' => array(1, 2, 3) )); 
$city_names = array( 'delhi', 'mumbai', 'kolkata', 'chennai' ); $city_query = http_build_query(array('city' => $city_names)); 
city[0]=delhi&city[1]=mumbai&city[2]=kolkata&city[3]=chennai 

if you want to encode the brackets also then use the below code:

$city_query = urlencode(http_build_query(array('city' => $city_names))); 
city%255B0%255D%3Ddelhi%26city%255B1%255D%3Dmumbai . 

Just repeat your $_GET variables like this: name=john&name=lea

I used to believe it would be overwritten!

Array get() Method in Java, Syntax. Array.get (Object []array, int index) Parameters : This method accepts two mandatory parameters: array: The object array whose index is to be returned. index: The particular index of the given array. The element at ‘index’ in the given array is returned. Return Value: This method returns the element of …

How to get PHP $_GET array?

Is it possible to have a value in $_GET as an array?

If I am trying to send a link with http://link/foo.php?id=1&id=2&id=3 , and I want to use $_GET[‘id’] on the php side, how can that value be an array? Because right now echo $_GET[‘id’] is returning 3 . Its the last id which is in the header link. Any suggestions?

The usual way to do this in PHP is to put id[] in your URL instead of just id :

Then $_GET[‘id’] will be an array of those values. It’s not especially pretty, but it works out of the box.

You could make id a series of comma-seperated values, like this:

Then, within your PHP code, explode it into an array:

$values = explode(",", $_GET["id"]); print count($values) . " values passed."; 

This will maintain brevity. The other (more commonly used with $_POST) method is to use array-style square-brackets:

Читайте также:  Source data line java

But that clearly would be much more verbose.

You can specify an array in your HTML this way:

This will result in this $_GET array in PHP:

array( 'id' => array( 0 => 1, 1 => 2, 2 => 3 ) ) 

Of course, you can use any sort of HTML input, here. The important thing is that all inputs whose values you want in the ‘id’ array have the name id[] .

You can get them using the Query String:

$idArray[0] = "id=1"; $idArray[1] = "id=2"; $idArray[2] = "id=3"; 
foreach ($idArray as $index => $avPair)

Arrays — C# Programming Guide, Array is the abstract base type of all array types. You can use the properties and other class members that Array has. An example of this is using the Length property to get the length of an array. The following code assigns the length of the numbers array, which is 5, to a variable called lengthOfNumbers:

Send array with GET Request

I am making a get request form Javascript to Python. And I am trying to pass a 2D array so something like

And here is what I am currently trying but it is not working.

So in my javascript I have an array that look similar to the one above, and then pass it like this

var xmlHttp = new XMLHttpRequest(); xmlHttp.open( "GET", "http://192.67.64.41/cgi-bin/hi.py?array=" + myArray, false ); xmlHttp.send( null ); 

And then in python I get it like this

import cgi form = cgi.FieldStorage() array = form.getvalue("array") 

But it doesn’t come out right, in python then if I were to do

print array[0] #I get -> "o" print array[1] #I get -> "n" print array[2] #I get -> "e" 

and so on, but if I what I want is

print array[0] #output -> ["one", "two"] 

How can I accomplish this?

You can’t simply Pass an Array as a query parameter. You will need to iterate over the array and add it so the URL string such as ?array[]=one&array[]=two

Here is a basic jsfiddle as an example

var a=['one', 'two']; var url = 'www.google.com'; for (var i=0; ielse < url = url + '&array[]=' + a[i]; >> console.log(url); 

No, you don’t have to. And, yes, you can do just that! You can pass it as one string like you did, and then get it and evaluate it in Python.

evaldict = <> array = eval("[[1, 2, 3], [4, 5, 6]]", evaldict) 

Although I forced the scope of evaluation to be encapsulated in a dict, THIS IS NOT SECURE!

Because someone can pass some other Python expression to be evaluated. Therefore better use literal_eval() from ast module which doesn’t evaluate expressions.

I suggest you tu use jquery and its post() method to do this, use a POST HTTP method instead of GET.

Also, this could be nice and securely done using json (send the json instead of just stringifying JS array manually. And using it to avoid evaluating a list directly (in Python).

Читайте также:  What is full stack php developer

Here is the client side using jquery:

    );">Click me! 

And this is the server-side CGI:

#! /usr/bin/env python try: # This version of eval() ensures only datatypes are evaluated # and no expressions. Safe version of eval() although slower. It is available in Python 2.6 and later from ast import literal_eval as eval except ImportError: import sys print "Content-Type: text/html\n" print "

literal_eval() not available!

" sys.exit() import cgi, cgitb import sys cgitb.enable() print "Content-Type: text/html\n" i = cgi.FieldStorage() q = i["array"].value.strip() print "I received:
" print q # Put here something to eliminate eventual malicious code from q # Check whether we received a list: if not q.startswith("[") and not q.endswith("]"): print "Wrong query!" sys.exit() try: myArray = eval(q) except: print "Wrong query!"; sys.exit() if not isinstance(myArray, list): print "Wrong query!" sys.exit() print "
Evaluated as:
" print myArray

Now, note that using json on both sides would be faster and more flexible.

Using arrays (VBA), In Visual Basic, you can declare arrays with up to 60 dimensions. For example, the following statement declares a 2-dimensional, 5-by-10 array. VB Copy Dim sngMulti (1 To 5, 1 To 10) As Single If you think of the array as a matrix, the first argument represents the rows and the second argument represents the …

Passing array in GET for a REST call

I have a url to fetch appointments for a user like this:

How should the url look like if I want to get appointments for multiple users?

Collections are a resource so /appointments is fine as the resource.

Collections also typically offer filters via the querystring which is essentially what users=id1,id2. is.

is fine as a filtered RESTful resource.

I think it’s a better practice to serialize your REST call parameters, usually by JSON-encoding them:

Then you un-encode them on the server. This is going to give you more flexibility in the long run.

Just make sure to URLEncode the params as well before you send them!

Another way of doing that, which can make sense depending on your server architecture/framework of choice, is to repeat the same argument over and over again. Something like this:

/appointments?users=id1&users=id2 

In this case I recommend using the parameter name in singular:

/appointments?user=id1&user=id2 

This is supported natively by frameworks such as Jersey (for Java). Take a look on this question for more details.

Array.GetValue Method (System), A 32-bit integer that represents the position of the Array element to get. Returns Object The value at the specified position in the one-dimensional Array. Exceptions ArgumentException The current Array does not have exactly one dimension. IndexOutOfRangeException index is outside the range of valid indexes for the …

Источник

Оцените статью