Как вы переиндексировать массив в PHP?
Это замечательно, в качестве альтернативы вы можете попробовать использовать array_unshift ($ arr, »), чтобы добавить элемент с нулевым индексом, а затем сбросить ($ arr [0]), чтобы удалить его, тем самым переместив все индексы на один. Это может быть быстрее, чем array_combine (). Или нет 🙂
Вот лучший способ:
# Array $array = array('tomato', '', 'apple', 'melon', 'cherry', '', '', 'banana');
Array ( [0] => tomato [1] => [2] => apple [3] => melon [4] => cherry [5] => [6] => [7] => banana )
$array = array_values(array_filter($array));
Array ( [0] => tomato [1] => apple [2] => melon [3] => cherry [4] => banana )
array_values() : Возвращает значения входного массива и индексов численно.
array_filter() : Фильтрует элементы массива с определяемой пользователем функцией (UDF Если ни один не указан, все записи в таблице входных значений FALSE будут удалены.)
Я только что узнал, что вы также можете сделать
Это делает повторную индексацию inplace, поэтому вы не получаете копию исходного массива.
Почему переиндексация? Просто добавьте 1 к индексу:
foreach ($array as $key => $val) < echo $key + 1, '
'; >
Изменить. После того, как вопрос будет уточнен: вы можете использовать array_values to reset индекс, начинающийся с 0. Затем вы можете использовать вышеприведенный алгоритм, если хотите просто начать печатные элементы при 1.
Хорошо, мне хотелось бы думать, что для любой цели, на самом деле вам не нужно было бы изменять массив, чтобы он был основан на 1, а не на основе 0, но вместо этого мог обрабатывать его на итерационном времени, таком как Gumbo вывешенным.
Однако, чтобы ответить на ваш вопрос, эта функция должна преобразовывать любой массив в 1-разрядную версию
function convertToOneBased( $arr )
ИЗМЕНИТЬ
Здесь более многоразовая/гибкая функция, если вы хотите ее
$arr = array( 'a', 'b', 'c' ); echo ''; print_r( reIndexArray( $arr ) ); print_r( reIndexArray( $arr, 1 ) ); print_r( reIndexArray( $arr, 2 ) ); print_r( reIndexArray( $arr, 10 ) ); print_r( reIndexArray( $arr, -10 ) ); echo ''; function reIndexArray( $arr, $startAt=0 )
Вы можете переиндексировать массив, чтобы новый массив начинался с индекса 1 следующим образом:
$arr = array( '2' => 'red', '1' => 'green', '0' => 'blue', ); $arr1 = array_values($arr); // Reindex the array starting from 0. array_unshift($arr1, ''); // Prepend a dummy element to the start of the array. unset($arr1[0]); // Kill the dummy element. print_r($arr); print_r($arr1);
Вывод из приведенного выше:
Array ( [2] => red [1] => green [0] => blue ) Array ( [1] => red [2] => green [3] => blue )
$list = array_combine(range(1, count($list)), array_values($list));
Это сделает то, что вы хотите:
'a', 1 => 'b', 0 => 'c'); array_unshift($array, false); // Add to the start of the array $array = array_values($array); // Re-number // Remove the first index so we start at 1 $array = array_slice($array, 1, count($array), true); print_r($array); // Array ( [1] => a [2] => b [3] => c ) ?>
Подобно @monowerker, мне нужно было переиндексировать массив, используя ключ объекта.
$new = array(); $old = array( (object)array('id' => 123), (object)array('id' => 456), (object)array('id' => 789), ); print_r($old); array_walk($old, function($item, $key, &$reindexed_array) < $reindexed_array[$item->id] = $item; >, &$new); print_r($new);
Array ( [0] => stdClass Object ( [id] => 123 ) [1] => stdClass Object ( [id] => 456 ) [2] => stdClass Object ( [id] => 789 ) ) Array ( [123] => stdClass Object ( [id] => 123 ) [456] => stdClass Object ( [id] => 456 ) [789] => stdClass Object ( [id] => 789 ) )
Возможно, вам захочется рассмотреть, почему вы хотите использовать массив на основе 1. Массивы с нулевым значением (при использовании неассоциативных массивов) довольно стандартизированы, и если вы хотите выводить на пользовательский интерфейс, большинство из них будут обрабатывать решение, просто увеличивая целое число после вывода в пользовательский интерфейс.
Подумайте о согласованности — как в своем приложении, так и в коде, с которым работаете — когда думаете о индексаторах на основе 1 для массивов.
Это напрямую связано с разделением между бизнес-уровнем и уровнем представления. Если вы изменяете код в своей логике, чтобы приспособить презентацию, вы делаете плохие вещи. Например, если вы сделали это для контроллера, ваш контроллер внезапно привязывается к определенному представлению представления, а скорее готовит данные для любого средства отображения представления, которое он может использовать (php, json, xml, rss и т. Д.)
Если вы не пытаетесь изменить порядок массива, вы можете просто:
$array = array_reverse ($ array);
$ array = array_reverse ($ array);Массив_реверс очень быстрый, и он меняет порядок, когда он меняет направление. Кто-то еще показал мне это давным-давно. Поэтому я не могу смириться с этим. Но это очень просто и быстро.
Как переиндексировать php массив
Если требуется переиндексировать массив и начать его не с 0, а с любого другого номера, то можно воспользоваться комбинацией нескольких встроенных функций PHP:
array_combine — Создаёт новый массив, используя один массив в качестве ключей, а другой для его значений.
Более подробное описание функции можно найти в документации php.net.
$array = [2 => 'fruit1', 5 => 'fruit2', 10 => 'fruit3', 14 => 'fruit4']; $keys = range(1, 4); $result = array_combine($keys, $array); print_r($result); // => [1 => 'fruit1', 2 => 'fruit2', 3 => 'fruit3', 4 => 'fruit4']
Solve PHP reindex array: single and multi-dimensional arrays
Posted on Sep 22, 2022
Sometimes, your PHP code will create an array that has gaps in its keys as shown below:
Nathan Jack Jessie In the above example, the array keys are unordered as it goes from 1 to 6 to 10 .To reindex the array keys of the array, you need to call the arra_values() function on your array.
See the code example below:
The print_r output will be:The array_values() only works for a single-dimension array.
When you need to reindex a multi-dimensional array, you need to call the array_map() function and pass array_values as its first parameter:
Array Nathan PHP developer Array Jack JavaScript developer Note that only the child arrays are being reindexed with the array_map() .This is because the array_map() function runs the array_values() function for each child element of the array.
To reindex both parent and child arrays, you need to call array_values() again:
Now both parent and child array keys will be reset:Array Nathan PHP developer Array Jack JavaScript developer But keep in mind that this trick won’t work when you have an unstructured array.Suppose you have an array with the following structure:
Calling the array_map() function will result in a fatal error:
To reindex an unstructured multi-dimensional array, you need to create a custom function.
This function needs to loop over the array and call array_values() on all values that are an array type.
The function below should be good:
Let’s test running the arra_reset() function:The code above produces the following output:Array Nathan PHP developer Array Jack JavaScript developer Jessie As you can see, both parent and child arrays are reindexed using the array_reset() function.This function is also able to reset the index of unstructured arrays, where the array value can be a non-array.
Feel free to use the array_reset() function in your code.
Now you’ve learned how to reindex a PHP array and reset its keys. Great job! 👍
Take your skills to the next level ⚡️
I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.Search
Type the keyword below and hit enter
Tags
Click to see all tutorials tagged with:
How to reset an array index in PHP
In this tutorial, we are going to learn about how to reset an array index in PHP.
Consider, that we are having the following PHP array with different indexes:
$cars = array( 3 => "audi", 4 => "benz", 2 => "ford", );
Now, we need to reset the above indexes numerically.
Resetting the array index
To reset the array index in PHP, we can use the built-in array_values() function in PHP.
The array_values() function takes the array as an argument and returns the array values with indexes numerically.
$cars = array( 3 => "audi", 4 => "benz", 2 => "ford", ); $reset = array_values($cars); print_r($reset);
Array ( [0] => audi [1] => benz [2] => ford )
You can also checkout the following tutorials for more knowledge: