разбить массив на переменные php
Функции для работы с массивами
Содержание
User Contributed Notes 14 notes
A simple trick that can help you to guess what diff/intersect or sort function does by name.
Example: array_diff_assoc, array_intersect_assoc.
Example: array_diff_key, array_intersect_key.
Example: array_diff, array_intersect.
Example: array_udiff_uassoc, array_uintersect_assoc.
This also works with array sort functions:
Example: arsort, asort.
Example: uksort, ksort.
Example: rsort, krsort.
Example: usort, uasort.
?>
Return:
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Cuatro [ 4 ] => Cinco [ 5 ] => Tres [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Tres [ 4 ] => Cuatro [ 5 ] => Cinco [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
?>
Updated code of ‘indioeuropeo’ with option to input string-based keys.
Here is a function to find out the maximum depth of a multidimensional array.
// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)
Short function for making a recursive array copy while cloning objects on the way.
If you need to flattern two-dismensional array with single values assoc subarrays, you could use this function:
to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.
to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);
You can also stringify objects, numbers, etc.
Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like so:
I was looking for an array aggregation function here and ended up writing this one.
Note: This implementation assumes that none of the fields you’re aggregating on contain The ‘@’ symbol.
While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.
Массивы
User Contributed Notes 17 notes
For newbies like me.
Creating new arrays:-
//Creates a blank array.
$theVariable = array();
//Creates an array with elements.
$theVariable = array(«A», «B», «C»);
//Creating Associaive array.
$theVariable = array(1 => «http//google.com», 2=> «http://yahoo.com»);
//Creating Associaive array with named keys
$theVariable = array(«google» => «http//google.com», «yahoo»=> «http://yahoo.com»);
Note:
New value can be added to the array as shown below.
$theVariable[] = «D»;
$theVariable[] = «E»;
To delete an individual array element use the unset function
output:
Array ( [0] => fileno [1] => Array ( [0] => uid [1] => uname ) [2] => topingid [3] => Array ( [0] => touid [1] => Array ( [0] => 1 [1] => 2 [2] => Array ( [0] => 3 [1] => 4 ) ) [2] => touname ) )
when I hope a function string2array($str), «spam2» suggest this. and It works well
hope this helps us, and add to the Array function list
Another way to create a multidimensional array that looks a lot cleaner is to use json_decode. (Note that this probably adds a touch of overhead, but it sure does look nicer.) You can of course add as many levels and as much formatting as you’d like to the string you then decode. Don’t forget that json requires » around values, not ‘!! (So, you can’t enclose the json string with » and use ‘ inside the string.)
Converting a linear array (like a mysql record set) into a tree, or multi-dimensional array can be a real bugbear. Capitalizing on references in PHP, we can ‘stack’ an array in one pass, using one loop, like this:
$node [ ‘leaf’ ][ 1 ][ ‘title’ ] = ‘I am node one.’ ;
$node [ ‘leaf’ ][ 2 ][ ‘title’ ] = ‘I am node two.’ ;
$node [ ‘leaf’ ][ 3 ][ ‘title’ ] = ‘I am node three.’ ;
$node [ ‘leaf’ ][ 4 ][ ‘title’ ] = ‘I am node four.’ ;
$node [ ‘leaf’ ][ 5 ][ ‘title’ ] = ‘I am node five.’ ;
Hope you find it useful. Huge thanks to Nate Weiner of IdeaShower.com for providing the original function I built on.
If an array item is declared with key as NULL, array key will automatically be converted to empty string », as follows:
A small correction to Endel Dreyer’s PHP array to javascript array function. I just changed it to show keys correctly:
function array2js($array,$show_keys)
<
$dimensoes = array();
$valores = array();
Made this function to delete elements in an array;
?>
but then i saw the methods of doing the same by Tyler Bannister & Paul, could see that theirs were faster, but had floors regarding deleting multiple elements thus support of several ways of giving parameters. I combined the two methods to this to this:
?>
Fast, compliant and functional 😉
//Creating a multidimensional array
/* 2. Works ini PHP >= 5.4.0 */
var_dump ( foo ()[ ‘name’ ]);
/*
When i run second method on PHP 5.3.8 i will be show error message «PHP Fatal error: Can’t use method return value in write context»
array_mask($_REQUEST, array(‘name’, ’email’));
extract
(PHP 4, PHP 5, PHP 7, PHP 8)
extract — Импортирует переменные из массива в текущую таблицу символов
Описание
Импортирует переменные из массива в текущую таблицу символов.
Каждый ключ проверяется на предмет корректного имени переменной. Также проверяются совпадения с существующими переменными в символьной таблице.
Список параметров
Возвращаемые значения
Возвращает количество переменных, успешно импортированных в текущую таблицу символов.
Примеры
Пример #1 Пример использования extract()
Результат выполнения данного примера:
Примечания
Смотрите также
User Contributed Notes 31 notes
They say «If the result is not a valid variable name, it is not imported into the symbol table.»
What they should say is that if _any_ of the results have invalid names, _none_ of the variables get extracted.
Under 4.3.10 on Windows 2000, I was pulling some mySQL records, but needed to convert two fields into IP addresses:
I had forgotten the second AS modifier in the SQL query. Because it couldn’t extract a variable called INET_NTOA(baz) into the symbol table, it didn’t do either of them.
(BTW I don’t normally stack functions up like that! Just to make a short example!)
[New Version]
This function is very useful for filtering complicated array structure.
Also, Some integer bitmasks and invalid UTF-8 sequence detection are available.
Example Usage:
[ ‘A’ ][ ‘a’ ] = ‘ CORRECT(including some spaces) ‘ ;
$_GET [ ‘A’ ][ ‘b’ ] = ‘ CORRECT(including some spaces) ‘ ;
$_GET [ ‘A’ ][ ‘c’ ] = «Invalid UTF-8 sequence: \xe3\xe3\xe3» ;
$_GET [ ‘A’ ][ ‘d’ ][ ‘invalid_structure’ ] = ‘INVALID’ ;
$_GET [ ‘B’ ][ ‘a’ ] = ‘ CORRECT(including some spaces) ‘ ;
$_GET [ ‘B’ ][ ‘b’ ] = «Invalid UTF-8 sequence: \xe3\xe3\xe3» ;
$_GET [ ‘B’ ][ ‘c’ ][ ‘invalid_structure’ ] = ‘INVALID’ ;
$_GET [ ‘B’ ][ «Invalid UTF-8 sequence: \xe3\xe3\xe3» ] = ‘INVALID’ ;
$_GET [ ‘C’ ][ ‘a’ ] = ‘ CORRECT(including some spaces) ‘ ;
$_GET [ ‘C’ ][ ‘b’ ] = «Invalid UTF-8 sequence: \xe3\xe3\xe3» ;
$_GET [ ‘C’ ][ ‘c’ ][ ‘invalid_structure’ ] = ‘INVALID’ ;
$_GET [ ‘C’ ][ «Invalid UTF-8 sequence: \xe3\xe3\xe3» ] = ‘INVALID’ ;
$_GET [ ‘unneeded_item’ ] = ‘UNNEEDED’ ;
Following up on ktwombley at gmail dot com’s post:
Presumably one easy way of dealing with this security issue is to use the EXTR_IF_EXISTS flag and make sure
a) your define acceptable input variables beforehand (i.e. as empty variables)
b) Sanitise any user input to avoid unacceptable variable content.
If you do these two things, then I’m not sure I see the difference between extract($_REQUEST,EXTR_IF_EXISTS); and assigning each of the variables by hand.
I’m not talking here about the idea of storing the variables in a database, just the immediately necessary steps to allow you to use extract on REQUEST arrays with relative safety.
Using extract’s return parameter can lead to unintended results, particularly with EXTR_REFS:
When extracting from a row after a database query using for example:
$row = mysql_fetch_array($result, MYSQL_ASSOC)
extract($row);
I find that the resultant variables may not match the variable type in the database. In particular I have found integers in the database may gettype() to string on the extracted variable.
Notice: Undefined variable: 1 in /Users/Lutashi/t.php on line 7
NULL
Sometimes you may want to extract only a named subset of the key/value pairs in an array. This keeps things more orderly and could prevent an unrelated variable from getting clobbered from an errant key. For example,
$things = ‘unsaid’;
$REQUEST = array(He=>This, said=>1, my=>is, info=>2, had=>a,
very=>3, important=>test, things=>4);
$aVarToExtract = array(my, important, info);
extract (array_intersect_key ($REQUEST, array_flip($aVarToExtract)));
will extract
$my = ‘is’;
$important = ‘test’;
$info = 2;
but will leave certain
$things = ‘unsaid’
For instance, the submission by kake26 at gmail dot com will not only perfectly emulate register globals (that’s bad), but it’ll store it in a database and recall the same variables every time the script runs (essentially allowing an attacker to attack your script every time it runs via one attack). Oops!
Dan O’Donnell’s suggestion needs a third requirement to work as described:
Without that condition the difference between extract() and assigning variables by hand (and the resulting security implications) should be obvious.
It is possible to use this as a way to create public attributes for a class.
As shown in the example, if your ‘prefix’ is used, a single underscore is added to the name of the extracted variable. Meaning, a prefix of ‘p’ becomes a prefix of ‘p_’, so ‘blarg’ prefixed would be ‘p_blarg’.
If you’re not sure what variables you’ve created through extraction, you can call get_defined_vars() to see all defined variables in the current scope.
Re: anon at anon dot org, about extract() and null values
Personally I’ve found use extracting multiple resultsets from db where the latter would overwrite the previous when a variable is not null ( and optionally if its not >0 )
with something like this:
EXTR_OVERWRITE_NULL
— If there is a collision, overwrite the existing variable if it is null
EXTR_OVERWRITE_0
— Same thing but == 0 or null
EXTR_SKIP_NULL
— If there is a collision, skip the new variable if the existing is not null
EXTR_SKIP_0
— Same thing but == 0 or null
Those ought to cover a few good cases that aren’t covered now.
A warning about extract() and null values.
This might be an actual Zend2 Engine bug, but it’s bad programming practice, so I’m sharing it here instead.
I often work in envrionments where E_STRICT (which would prevent errors like this) isn’t on, and I don’t have access to change it. I also use a very simple template class that in a nutshell works like this:
display() more or less looks like this:
In a nutshell, if you start getting wierd behavior when using extract() make sure that the array or object you are trying to get variables out of doesn’t contain null keys or values!
In response to Dan O’Donnell’s note:
«Presumably one easy way of dealing with this security issue is to use the EXTR_IF_EXISTS flag and make sure»
seems all well and good if we had a url like
as that would specifically find joe bloggs of 20 any street.
however what if someone typed in
SELECT table_name FROM information_schema.tables
could be a real disaster!
Of course, this is only a basic example, but it could be quite easy to forget about global variables and these global variables could quite easily be used with extract to cause serious security risks if GET, REQUEST or POST is sent to extract!
We can use extract () function for Template Engine:
Page Header
This is the content page
Here is a little example of how an extraction method should look like when it needs to work recursive (work on nested_arrays too).
Note that this is only an example, it can be done more easily, and more advanced too.
In the meantime, I’m using this:
// extract alternative
# extracts variables where new value is above the threshold or if old value is on or below the threshold (or var is not defined)
# an associative array is obviously the sane thing to pass
#
# I am absolutely certain someone will find obvious problems or errors with this
# I haven’t even tried to compare other values than 0 so if you need to do that and surely finds obvious flaws,
# please mail me, I’d really like to know.
# benjaminATwebbutvecklarnaDOTse
// usage example:
# thrextract(mysql_fetch_assoc(mysql_query(«SELECT preset_this,preset_that FROM site_preset WHERE /># thrextract(mysql_fetch_assoc(mysql_query(«SELECT preset_this,preset_that FROM category_preset WHERE
Besides I teach PHP in a school, and this function has made my examples easier.
array
(PHP 4, PHP 5, PHP 7, PHP 8)
array — Создаёт массив
Описание
Создаёт массив. Подробнее о массивах читайте в разделе Массивы.
Список параметров
Наличие завершающей запятой после последнего элемента массива, несмотря на некоторую необычность, является корректным синтаксисом.
Возвращаемые значения
Примеры
Последующие примеры демонстрируют создание двухмерного массива, определение ключей ассоциативных массивов и способ генерации числовых индексов для обычных массивов, если нумерация начинается с произвольного числа.
Пример #1 Пример использования array()
Пример #2 Автоматическая индексация с помощью array()
Результат выполнения данного примера:
Этот пример создаёт массив, нумерация которого начинается с 1.
Результат выполнения данного примера:
Как и в Perl, вы имеете доступ к значениям массива внутри двойных кавычек. Однако в PHP нужно заключить ваш массив в фигурные скобки.
Пример #4 Доступ к массиву внутри двойных кавычек
Примечания
Смотрите также
User Contributed Notes 38 notes
As of PHP 5.4.x you can now use ‘short syntax arrays’ which eliminates the need of this function.
So, for example, I needed to render a list of states/provinces for various countries in a select field, and I wanted to use each country name as an label. So, with this function, if only a single array is passed to the function (i.e. «arrayToSelect($stateList)») then it will simply spit out a bunch of » » elements. On the other hand, if two arrays are passed to it, the second array becomes a «key» for translating the first array.
Here’s a further example:
$countryList = array(
‘CA’ => ‘Canada’,
‘US’ => ‘United States’);
$stateList[‘CA’] = array(
‘AB’ => ‘Alberta’,
‘BC’ => ‘British Columbia’,
‘AB’ => ‘Alberta’,
‘BC’ => ‘British Columbia’,
‘MB’ => ‘Manitoba’,
‘NB’ => ‘New Brunswick’,
‘NL’ => ‘Newfoundland/Labrador’,
‘NS’ => ‘Nova Scotia’,
‘NT’ => ‘Northwest Territories’,
‘NU’ => ‘Nunavut’,
‘ON’ => ‘Ontario’,
‘PE’ => ‘Prince Edward Island’,
‘QC’ => ‘Quebec’,
‘SK’ => ‘Saskatchewan’,
‘YT’ => ‘Yukon’);
$stateList[‘US’] = array(
‘AL’ => ‘Alabama’,
‘AK’ => ‘Alaska’,
‘AZ’ => ‘Arizona’,
‘AR’ => ‘Arkansas’,
‘CA’ => ‘California’,
‘CO’ => ‘Colorado’,
‘CT’ => ‘Connecticut’,
‘DE’ => ‘Delaware’,
‘DC’ => ‘District of Columbia’,
‘FL’ => ‘Florida’,
‘GA’ => ‘Georgia’,
‘HI’ => ‘Hawaii’,
‘ID’ => ‘Idaho’,
‘IL’ => ‘Illinois’,
‘IN’ => ‘Indiana’,
‘IA’ => ‘Iowa’,
‘KS’ => ‘Kansas’,
‘KY’ => ‘Kentucky’,
‘LA’ => ‘Louisiana’,
‘ME’ => ‘Maine’,
‘MD’ => ‘Maryland’,
‘MA’ => ‘Massachusetts’,
‘MI’ => ‘Michigan’,
‘MN’ => ‘Minnesota’,
‘MS’ => ‘Mississippi’,
‘MO’ => ‘Missouri’,
‘MT’ => ‘Montana’,
‘NE’ => ‘Nebraska’,
‘NV’ => ‘Nevada’,
‘NH’ => ‘New Hampshire’,
‘NJ’ => ‘New Jersey’,
‘NM’ => ‘New Mexico’,
‘NY’ => ‘New York’,
‘NC’ => ‘North Carolina’,
‘ND’ => ‘North Dakota’,
‘OH’ => ‘Ohio’,
‘OK’ => ‘Oklahoma’,
‘OR’ => ‘Oregon’,
‘PA’ => ‘Pennsylvania’,
‘RI’ => ‘Rhode Island’,
‘SC’ => ‘South Carolina’,
‘SD’ => ‘South Dakota’,
‘TN’ => ‘Tennessee’,
‘TX’ => ‘Texas’,
‘UT’ => ‘Utah’,
‘VT’ => ‘Vermont’,
‘VA’ => ‘Virginia’,
‘WA’ => ‘Washington’,
‘WV’ => ‘West Virginia’,
‘WI’ => ‘Wisconsin’,
‘WY’ => ‘Wyoming’);
Массивы в php
Организация массива
Как писалось выше, массив состоит из элементов, каждый из которых имеет ключ и значение. Например массив содержащий информацию о ценах в ресторанном меню может выглядеть так:
Ключ | Значение |
---|---|
0 | 700 |
1 | 1500 |
2 | 1100 |
Рассмотрим пример:
В первом случае элементы массива представляют из себя пару ключ-значение, где в качестве ключа используются строковые названия «блюд» (приёмов пищи на самом деле, но пусть будет блюд), а значение это цена блюда. Во втором же случае я указал только цены, при этом интерпретатор PHP автоматически проставит ключи элементам массива.
Операции с массивами
Один из случаев ключевой операции с массивами, а именно его создание мы рассмотрели выше. А как ещё можно создать массив? Самый простой случай, это создание пустого массива:
Создание и модификация массива
Пустой массив может служить заготовкой под определённую коллекцию данных. Конечно его можно не определять заранее и создать прямо в цикле где он должен заполняться, но тогда это будет менее понятный код.
Вы так же можете заполнить массив на лету, например данными из базы данных:
Перебор массивов
С другой стороны готовый массив можно перебрать и например вывести его элементы на экран:
Вообще в php существует больше 70 функций для работы с массивами, однако в большинстве случаев вы будет использовать не больше двадцати. Приведу некоторые из них:
Сортировка массива
В результате выполнения данного примера получим такой массив:
Вы так же можете пробросить в тело функции compare() внешнюю переменную используя анонимную функцию и ключевое слово use :
Глобальные массивы
Многомерные массивы
Как вы уже знаете, элементы массива могут содержать в качестве значения данные любого типа, строки, числа, логические, в том числе и другие массивы. Массив состоящий из других массивов называется многомерным или вложенным массивом. На практике используется 2-3 уровня вложенности для хранения каких-либо связанных структурных данных (например данных о покупателях магазина или каталоге товаров), обработка массивов большей вложенности усложняется и используется не часто.
Давайте разберёмся как создавать и взаимодействовать с многомерными массивами.
Создание многомерных массивов
В первую очередь создадим простой двумерный массив сотрудников организации:
Обратите внимание что в «родительском» массиве мы не указывали символьных ключей, поэтому массивам внутри были просто присвоены числовые индексы 0, 1, 2. Давайте теперь распределим наших сотрудников по отделам и добавим ещё одного сотрудника.
Теперь мы имеем многомерный массив в котором на «первом уровне» хранятся отделы компании, а уже внутри отделов сотрудники. При этом отдел имеет символьный ключ, например DEPARTMENT_IT — отдел IT. Немного усложним наш пример и добавим информацию о наименовании отделов и времени работы, а сотрудников отдела поместим на уровень ниже:
Как видите используя многомерные массивы можно строить довольно сложные структуры данных с которыми в последствии предстоит работать нашему веб-приложению.
Доступ к элементам многомерного массива
Рассмотрим как получить доступ к элементам многомерного массива. В качестве примера возьмём выше описанные массивы сотрудников компании. Но перед этим предлагаю набросать небольшую функцию, которая позволит удобно просматривать содержимое переменных в вашем коде. Я часто использую её в работе:
И так, давайте узнаем имена и возраст всех сотрудников из первого двумерного массива:
Получим такую страницу:
Таким образом можно вывести например страницу контактов сайта, на которой должны быть «координаты» должностных лиц отвечающих за то или иное направление деятельности компании. Оформление сами понимаете зависит от вашей фантазии и дизайна сайта.
Обработка многомерного массива
Один из примеров обработки массива был представлен выше, когда мы просто вывели на экран содержимое многомерного массива в удобном для пользователя виде. Однако это далеко не всё что можно делать с массивами. Например мы можешь осуществить некий поиск по элементам узнать сколько сотрудников старше 30 лет работает в нашей компании:
Существует множество примеров обработки массивов в PHP, но они выходят за рамки данной статьи.