php сдвинуть индексы массива
array_flip
(PHP 4, PHP 5, PHP 7, PHP 8)
array_flip — Меняет местами ключи с их значениями в массиве
Описание
Функция array_flip() возвращает массив ( array ) наоборот, то есть ключи массива array становятся значениями, а значения массива array становятся ключами.
Если значение встречается несколько раз, для обработки будет использоваться последний встреченный ключ, а все остальные будут потеряны.
Список параметров
Массив переворачиваемых пар ключ/значение.
Возвращаемые значения
Возвращает перевёрнутый массив в случае успешного выполнения и null в случае возникновения ошибки.
Примеры
Пример #1 Пример использования array_flip()
Результат выполнения данного примера:
Пример #2 Пример использования array_flip() с коллизиями
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 18 notes
This function is useful when parsing a CSV file with a heading column, but the columns might vary in order or presence:
?>
I find this better than referencing the numerical array index.
array_flip will remove duplicate values in the original array when you flip either an associative or numeric array. As you might expect it’s the earlier of two duplicates that is lost:
array(3) <
[0] => string(3) «one»
[1] => string(3) «two»
[2] => string(3) «one»
>
This may be good or bad, depending on what you want, but no error is thrown.
array_flip() does not retain the data type of values, when converting them into keys. 🙁
It is valid expectation that string values «1», «2» and «3» would become string keys «1», «2» and «3».
When you do array_flip, it takes the last key accurence for each value, but be aware that keys order in flipped array will be in the order, values were first seen in original array. For example, array:
In my application I needed to find five most recently commented entries. I had a sorted comment-id => entry-id array, and what popped in my mind is just do array_flip($array), and I thought I now would have last five entries in the array as most recently commented entry => comment pairs. In fact it wasn’t (see above, as it is the order of values used). To achieve what I need I came up with the following (in case someone will need to do something like that):
First, we need a way to flip an array, taking the first encountered key for each of values in array. You can do it with:
Well, and to achieve that «last comments» effect, just do:
$array = array_reverse($array, true);
$array = array_flip(array_unique($array));
$array = array_reverse($array, true);
In the example from the very beginning array will become:
Just what I (and maybe you?) need. =^_^=
In case anyone is wondering how array_flip() treats empty arrays:
( array_flip (array()));
?>
results in:
I wanted to know if it would return false and/or even chuck out an error if there were no key-value pairs to flip, despite being non-intuitive if that were the case. But (of course) everything works as expected. Just a head’s up for the paranoid.
I needed a way to flip a multidimensional array and came up with this function to accomplish the task. I hope it helps someone else.
Функции для работы с массивами
Содержание
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.
array_unshift
(PHP 4, PHP 5, PHP 7, PHP 8)
array_unshift — Добавляет один или несколько элементов в начало массива
Описание
Список параметров
Значения для добавления.
Возвращаемые значения
Список изменений
Версия | Описание |
---|---|
7.3.0 | Теперь эта функция может быть вызвана с одним параметром. Ранее требовалось минимум два параметра. |
Примеры
Пример #1 Пример использования array_unshift()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 12 notes
You can preserve keys and unshift an array with numerical indexes in a really simple way if you’ll do the following:
array(
100=>’Test Element 1 ‘,
255=>’Test Element 2′
224=>’someword1′,
228=>’someword2′,
102=>’someword3′,
544=>’someword3′,
95=>’someword4′
);
array_merge() will also reindex (see array_merge() manual entry), but the ‘+’ operator won’t, so.
Sahn’s example almost works but has a small error. Try it like this if you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:
Anonymous’ associative version wasn’t working for me, but it did with this small tweak:
Another way to tack something to the beginning of an array is with array_merge().
$plans = array(‘AARP’=>’Senior’, ‘AAA’=>’Automobile Club’);
Actually this problem with the keys getting reindexed only happens when the keys are numerical:
k: f v: five
k: s v: six
k: t v: twenty
Array
(
[0] => zero
[f] => five
[s] => six
[t] => twenty
)
k: 0 v: zero
k: f v: five
k: s v: six
k: t v: twenty
This becomes a nice little problem if you index your arrays out of order (while manually sorting). For example:
[ 3 ] = ‘8/%/2006’ ;
$recordMonths [ 4 ] = ‘7/%/2004’ ;
$recordMonths [ 0 ] = ‘3/%/2007’ ;
$recordMonths [ 1 ] = ‘2/%/2007’ ;
$recordMonths [ 5 ] = ’12/%/2000′ ;
$recordMonths [ 6 ] = ’11/%/2000′ ;
$recordMonths [ 7 ] = ’10/%/2000′ ;
$recordMonths [ 2 ] = ‘1/%/2007’ ;
singleMonth: 3/%/2007
singleMonth: 2/%/2007
singleMonth: 1/%/2007
singleMonth: 8/%/2006
singleMonth: 7/%/2004
singleMonth: 12/%/2000
singleMonth: 11/%/2000
singleMonth: 10/%/2000
singleMonth: %
singleMonth: 8/%/2006
singleMonth: 7/%/2004
singleMonth: 3/%/2007
singleMonth: 2/%/2007
singleMonth: 12/%/2000
singleMonth: 11/%/2000
singleMonth: 10/%/2000
singleMonth: 1/%/2007
It reindexes them based on the order they were created. It seems like if an array has all numeric indexes, then it should reindex them based on the order of their index. Just my opinion.
If you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:
If you need to change the name of a key without changing its position in the array this function may be useful.
I had a need tonight to convert a numeric array from 1-based to 0-based, and found that the following worked just fine due to the «side effect» of renumbering:
Last version of PHP deprecated unshifting of a reference.
You can use this function instead :