Обнулить индексы массива php
reset
(PHP 4, PHP 5, PHP 7, PHP 8)
reset — Устанавливает внутренний указатель массива на его первый элемент
Описание
reset() перемещает внутренний указатель массива array к его первому элементу и возвращает значение первого элемента массива.
Список параметров
Возвращаемые значения
Примеры
Пример #1 Пример использования reset()
Примечания
Смотрите также
User Contributed Notes 13 notes
GOTCHA: If your first element is false, you don’t know whether it was empty or not.
?>
So don’t count on a false return being an empty array.
As for taking first key of an array, it’s much more efficient to RESET and then KEY, rather then RESET result of ARRAY_KEYS (as sugested by gardnerjohng at gmail dot com).
Also it’s good to reset this way the multidimentional arrays:
Note that reset() will not affect sub-arrays of multidimensional array.
In response to gardnerjohng’s note to retrieve the first _key_ of an array:
To retrieve the first _key_ of an array you can use the combination of reset() and key().
Since reset() returns the first «value» of the array beside resetting its internal pointer; it will return different results when it is combined with key() or used separately. Like;
?>
This is perfectly normal because in the first method, reset() returned the first «value» of the ‘biscuits’ element which is to be «cbosi». So key(string) will cause a fatal error. While in the second method you just reset the array and didn’t use a returning value; instead you reset the pointer and than extracted the first key of an array.
If your array has more dimensions, it won’t probably cause a fatal error but you will get different results when you combine reset() and key() or use them consecutively.
Following code gives a strict warning in 5.4.45
«Strict warning: Only variables should be passed by reference»
$keys = array_keys($result[‘node’]);
return reset($keys);
I had a problem with PHP 5.0.5 somehow resetting a sub-array of an array with no apparent reason. The problem was in doing a foreach() on the parent array PHP was making a copy of the subarrays and in doing so it was resetting the internal pointers of the original array.
The following code demonstrates the resetting of a subarray:
Unfortunately for me, my key required to be more than just a simple string or number (if it was then it could be used to directly index the subarray of data for that object and problem avoided) but was an array of strings. Instead, I had to iterate over (with a foreach loop) each subarray and compare the key to a variable stored within the subarray.
So by using a foreach loop in this manner and with PHP resetting the pointer of subarrays it ended up causing an infinite loop.
Really, this could be solved by PHP maintaining internal pointers on arrays even after copying.
Функции для работы с массивами
Содержание
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.
Как вы переиндексировать массив в PHP?
У меня есть следующий массив, который я хотел бы переиндексировать, чтобы ключи поменялись местами (в идеале, начиная с 1):
Текущий массив (редактировать: массив на самом деле выглядит так):
Как это должно быть:
Решение
Если вы хотите переиндексировать, начиная с нуля, просто сделайте следующее:
Если вам нужно, чтобы начать с одного, то используйте следующее:
Вот справочные страницы для используемых функций:
Другие решения
Вот лучший способ:
объяснение
array_values() Возвращает значения входного массива и численно индексирует.
array_filter() : Фильтрует элементы массива с помощью пользовательской функции (UDF Если ничего не предоставлено, все записи во входной таблице со значением FALSE будут удалены.)
Почему переиндексация? Просто добавьте 1 к индексу:
редактировать После выяснения вопроса: вы можете использовать array_values сбросить индекс, начиная с 0. Тогда вы можете использовать алгоритм, приведенный выше, если вы просто хотите, чтобы напечатанные элементы начинались с 1.
Я только что узнал, что вы также можете сделать
Это делает переиндексацию на месте, поэтому вы не получите копию исходного массива.
Что ж, я хотел бы думать, что для любой вашей конечной цели вам на самом деле не нужно изменять массив, чтобы он был основан на 1, а не на 0, но вместо этого мог бы обрабатывать его во время итерации, как написал Гамбо.
тем не мение, чтобы ответить на ваш вопрос, эта функция должна конвертировать любой массив в версию на основе 1
РЕДАКТИРОВАТЬ
Вот более многоразовая / гибкая функция, если хотите
Это будет делать то, что вы хотите:
Более элегантное решение:
Вы можете переиндексировать массив, чтобы новый массив начинался с индекса 1 следующим образом;
array_values
(PHP 4, PHP 5, PHP 7, PHP 8)
array_values — Выбирает все значения массива
Описание
Список параметров
Возвращаемые значения
Возвращает индексированный массив значений.
Примеры
Пример #1 Пример использования array_values()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 25 notes
Remember, array_values() will ignore your beautiful numeric indexes, it will renumber them according tho the ‘foreach’ ordering:
Just a warning that re-indexing an array by array_values() may cause you to reach the memory limit unexpectly.
Doing this will cause PHP exceeds the momory limits:
Most of the array_flatten functions don’t allow preservation of keys. Mine allows preserve, don’t preserve, and preserve only strings (default).
echo ‘var_dump($array);’.»\n»;
var_dump($array);
echo ‘var_dump(array_flatten($array, 0));’.»\n»;
var_dump(array_flatten($array, 0));
echo ‘var_dump(array_flatten($array, 1));’.»\n»;
var_dump(array_flatten($array, 1));
echo ‘var_dump(array_flatten($array, 2));’.»\n»;
var_dump(array_flatten($array, 2));
?>
If you are looking for a way to count the total number of times a specific value appears in array, use this function:
I needed a function that recursively went into each level of the array to order (only the indexed) arrays. and NOT flatten the whole thing.
Remember, that the following way of fetching data from a mySql-Table will do exactly the thing as carl described before: An array, which data may be accessed both by numerical and DB-ID-based Indexes:
/*
fruit1 = apple
fruit2 = orange
fruit5 = apple
*/
?>
A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)
array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298
same array_flatten function, compressed and preserving keys.
/**********************************************
*
* PURPOSE: Flatten a deep multidimensional array into a list of its
* scalar values
*
* array array_values_recursive (array array)
*
* WARNING: Array keys will be lost
*
*********************************************/
Non-recursive simplest array_flatten.
A modification of wellandpower at hotmail.com’s function to perform array_values recursively. This version will only re-index numeric keys, leaving associative array indexes alone.
Please note that ‘wellandpower at hotmail.com’s recursive merge doesn’t work. Here’s the fixed version:
The function here flatterns an entire array and was not the behaviour I expected from a function of this name.
I expected the function to flattern every sub array so that all the values were aligned and it would return an array with the same dimensions as the imput array, but as per array_values() adjusting the keys rater than removing them.
In order to do this, you will want this function:
function array_values_recursive($array) <
$temp = array();
Hopefully this will assist.
Note that in a multidimensional array, each element may be identified by a _sequence_ of keys, i.e. the keys that lead towards that element. Thus «preserving keys» may have different interpretations. Ivan’s function for example creates a two-dimensional array preserving the last two keys. Other functions below create a one-dimensional array preserving the last key. For completeness, I will add a function that merges the key sequence by a given separator and a function that preserves the last n keys, where n is arbitrary.
/*
* Flattening a multi-dimensional array into a
* single-dimensional one. The resulting keys are a
* string-separated list of the original keys:
*
* a[x][y][z] becomes a[implode(sep, array(x,y,z))]
*/
Лучший способ очистить значения массива PHP
Что более эффективно для очистки всех значений в массиве? Первый из них потребовал бы, чтобы я использовал эту функцию каждый раз в цикле второго примера.
Как сказал Зак в комментариях ниже, вы можете просто повторно создать его, используя
Если вы просто хотите сбросить переменную в пустой массив, вы можете просто повторно инициализировать ее:
Обратите внимание, что это будет содержать ссылки на него:
Если вы хотите разорвать любые ссылки на него, сначала отключите его:
К сожалению, я не могу ответить на другие вопросы, не имею достаточной репутации, но мне нужно указать что-то, что было ОЧЕНЬ важно для меня, и я думаю, что это поможет другим людям.
Сброс переменной – отличный способ, если вам не нужна ссылка на исходный массив!
Чтобы понять, что я имею в виду: если у вас есть функция, использующая ссылку массива, например функцию сортировки, например
Я бы сказал, первый, если массив ассоциативный. Если нет, используйте цикл for :
Хотя, если это возможно, использование
Предпочтительным является сброс массива в пустой массив.
Не unset() достаточно хорошо?
Используйте array_splice для array_splice массива и сохранения ссылки:
Функция unset полезна, когда сборщик мусора делает свои раунды, не имея перерыва на обед;
однако функция unset просто уничтожает ссылку на переменные для данных, данные все еще существуют в памяти, и PHP видит, что память используется, несмотря на то, что у нее больше нет указателя на нее.
Решение. Назначьте null своим переменным, чтобы очистить данные, по крайней мере до тех пор, пока сборщик мусора не схватит его.
а затем отключить его аналогичным образом!
я использовал unset (), чтобы очистить массив, но я понял, что unset () будет отображать массив null, следовательно, необходимо повторно объявить массив, например, например
// делай то, что хочешь здесь
Это мощный и проверенный unset ($ gradearray); // повторно задает массив