php array to query string
Конвертировать массив в строку при помощи PHP
Если вам потребовалось преобразовать массив php в строку, то для этого есть несколько инструментов. Применение того или иного инструмента зависит от ваших целей.
Теперь поговорим о конвертации массива в строку:
1. Функция implode()
С ее помощью можно «склеить» элементы массива в строку, через любой разделитель. Подробнее: implode
Пример:
Подобным образом мы можем преобразовать только одномерные массивы и у нас пропадут ключи.
2. Функция join()
Работает точно так же как и implode(), поскольку это просто псевдоним, выбирайте название, которое больше нравится.
Пример у нас будет идентичный:
3. Функция serialize()
Затем из этой строки, можно снова получить массив:
4. Функция json_encode()
Возвращает JSON представление данных. В нашем случае, данная функция, напоминает сериализацию, но JSON в основном используется для передачи данных. Вам придется использовать этот формат для обмена данными с javascript, на фронтенде. Подробнее: json_encode
Обратная функция json_decode() вернет объект с типом stdClass, если вторым параметром функции будет false. Либо вернет ассоциативный массив, если передать true вторым параметром
5. Функция print_r
Она подходит для отладки вашего кода. Например вам нужно вывести массив на экран, чтобы понять, какие элементы он содержит.
6. Функция var_dump
Функция var_dump также пригодится для отладки. Она может работать не только с массивами, но и с любыми другими переменными, содержимое которых вы хотите проверить.
7. Функция var_export
var_dump не возвращает значение, но при желании это конечно можно сделать через буферизацию.
array_to_string
Как таковой функции array_to_string в php нет, но есть описанные выше инструменты, которых более чем достаточно для выполнения задачи. Я просто хотел напомнить, что вы никогда не ограничены этими инструментами, и можете написать то, что подходит именно под вашу задачу.
Как сделать работу с массивами еще проще?
Если вы используете библиотеку для работы с коллекциями, то ваш код для преобразования массива в строку может выглядеть куда более изящно:
Также рекомендую обратить внимание на полезную библиотеку для работы со строками. С ее помощью вы можете выполнять операции со строками более удобно и с меньшим количеством кода.
На этом все. Обязательно прочитайте справку по данным функциям и пишите если у вас остались вопросы.
parse_str
(PHP 4, PHP 5, PHP 7, PHP 8)
parse_str — Разбирает строку в переменные
Описание
Список параметров
Использовать эту функцию без параметра result крайне НЕ РЕКОМЕНДУЕТСЯ. Подобное использование объявлено УСТАРЕВШИМ с PHP 7.2.
Возвращаемые значения
Функция не возвращает значения после выполнения.
Список изменений
Примеры
Пример #1 Использование parse_str()
Пример #2 Соотношение имён parse_str()
Примечания
Смотрите также
User Contributed Notes 31 notes
It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields. If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them:
# silently fails to handle multiple values
parse_str ( ‘foo=1&foo=2&foo=3’ );
# the above produces:
$foo = array( ‘foo’ => ‘3’ );
?>
Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect.
# bizarre php-specific behavior
parse_str ( ‘foo[]=1&foo[]=2&foo[]=3’ );
if you need custom arg separator, you can use this function. it returns parsed query as associative array.
You may want to parse the query string into an array.
As of PHP 5, you can do the exact opposite with http_build_query(). Just remember to use the optional array output parameter.
This is a very useful combination if you want to re-use a search string url, but also slightly modify it:
Results in:
url1: action=search&interest[]=sports&interest[]=music&sort=id
url2: action=search&interest[0]=sports&interest[1]=music&sort=interest
(Array indexes are automatically created.)
CONVERT ANY FORMATTED STRING INTO VARIABLES
I developed a online payment solution for credit cards using a merchant, and this merchant returns me an answer of the state of the transaction like this:
to have all that data into variables could be fine for me! so i use str_replace(), the problem is this function recognizes each group of variables with the & character. and i have comma separated values. so i replace comma with &
Note that the characters «.» and » » (empty space) will be converted to «_». The characters «[» and «]» have special meaning: They represent arrays but there seems to be some weird behaviour, which I don’t really understand:
Here is a little function that does the opposite of the parse_str function. It will take an array and build a query string from it.
?>
Note that the function will also append the session ID to the query string if it needs to be.
The array to be populated does not need to be defined before calling the function:
http_build_query
http_build_query — Генерирует URL-кодированную строку запроса
Описание
Генерирует URL-кодированную строку запроса из предоставленного ассоциативного (или индексированного) массива.
Список параметров
Может быть массив или объект, содержащий свойства.
Если data массив, то он может быть простой одномерной структурой или массивом массивов (который, в свою очередь, может содержать другие массивы).
Если data объект, тогда только общедоступные свойства будут включены в результат.
Если числовые индексы используются в базовом массиве и этот параметр указан, то он будет добавлен к числовому индексу для элементов только в базовом массиве.
Это позволяет обеспечить допустимые имена переменных, в которые позже данные будут декодированы PHP или другим CGI-приложением.
arg_separator.output используется в качестве разделителя аргументов, но может быть переопределён путём указания этого параметра.
Возвращаемые значения
Возвращает URL-кодированную строку.
Примеры
Пример #1 Простой пример использования http_build_query()
Результат выполнения данного примера:
Пример #2 Пример использования http_build_query() с числовыми индексами элементов.
Результат выполнения данного примера:
Пример #3 Пример использования http_build_query() с многомерными массивами
Результат выполнения данных примеров: (символы перенесены для удобства чтения)
Только числовой индексированный элемент «CEO» в базовом массиве получил префикс. Другие числовые индексы, найденные в pastimes, не требуют строкового префикса, чтобы быть допустимыми именами переменных.
Пример #4 Пример использования http_build_query() с объектом
$parent = new parentClass ();
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 24 notes
Params with null value do not present in result string.
If you need to change the enc_type, use this:
http_build_query($query, null, ini_get(‘arg_separator.output’), PHP_QUERY_RFC3986);
// BAD CODE!
http_build_query($query, null, null, PHP_QUERY_RFC3986);
if you send boolean values it transform in integer :
$a = [teste1= true,teste2=false];
echo http_build_query($a)
//result will be teste1=1&teste2=0
This function makes like this
To do it like this:
As noted before, with php5.3 the separator is & on some servers it seems. Normally if posting to another php5.3 machine this will not be a problem.
But if you post to a tomcat java server or something else the & might not be handled properly.
To overcome this specify:
http_build_query($array); //gives & to some servers
It’s not mentioned in the documentation, but when calling http_build_query on an object, public null fields are ignored.
Is it worth noting that if query_data is an associative array and a value is itself an empty array, or an array of nothing but empty array (or arrays containing only empty arrays etc.), the corresponding key will not appear in the resulting query string?
E.g.
$post_data = array(‘name’=>’miller’, ‘address’=>array(‘address_lines’=>array()), ‘age’=>23);
echo http_build_query($post_data);
Instead you can make your own simple function if you simply want to pass along the data:
If you need the inverse functionality, and (like me) you cannot use pecl_http, you may want to use something akin to the following.
Parse query string into an array
How can I turn a string below into an array?
This is the array I am looking for,
11 Answers 11
You want the parse_str function, and you need to set the second parameter to have the data put in an array instead of into individual variables.
Sometimes parse_str() alone is note accurate, it could display for example:
parse_str() would return:
It would be better to combine parse_str() with parse_url() like so:
If you’re having a problem converting a query string to an array because of encoded ampersands
then be sure to use html_entity_decode
Attention, it’s usage is:
Please note that the above only applies to PHP version 5.3 and earlier. Call-time pass-by-reference has been removed in PHP 5.4
There are several possible methods, but for you, there is already a builtin parse_str function
This is one-liner for parsing query from current URL into array:
You can use the PHP string function parse_str() followed by foreach loop.
You can try this code :
This is the PHP code to split query in mysql & mssql
Query before
select xx from xx select xx,(select xx) from xx where y=’ cc’ select xx from xx left join ( select xx) where (select top 1 xxx from xxx) oder by xxx desc «;
Query after
select xx,(select xx) from xx where y=’ cc’
select xx from xx left join (select xx) where (select top 1 xxx from xxx) oder by xxx desc
Thank you, from Indonesia Sentrapedagang.com
For this specific question the chosen answer is correct but if there is a redundant parameter—like an extra «e»—in the URL the function will silently fail without an error or exception being thrown:
So I prefer using my own parser like so:
Now you have all the occurrences of each parameter in its own array, you can always merge them into one array if you want to.
How to convert an array to a string in PHP?
For an array like the one below; what would be the best way to get the array values and store them as a comma-separated string?
8 Answers 8
I would turn it into CSV form, like so:
You can turn it back by doing:
I would turn it into a json object, with the added benefit of keeping the keys if you are using an associative array:
serialize() and unserialize() convert between php objects and a string representation.
PHP has a built-in function implode to assign array values to string. Use it like this:
You can use it like so:
Not the answer you’re looking for? Browse other questions tagged php arrays or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.