Php reset array indexes

Reset keys of array elements using PHP ?

In PHP, two types of arrays are possible indexed and associative array. In case of Indexed array, the elements are strictly integer indexed and in case of associative array every element has corresponding keys associated with them and the elements can only be accessed using these keys.

To access the keys and values of an associative array using integer index the array_keys() and array_values() inbuilt functions can be used.

  • The array_keys() function takes input an array and returns the indexed array of only keys from the input array.
  • The array_values() function takes input an array and return the indexed array of only values from the input array.

Now, to reset the keys of array elements two operations can be performed, key_swap() and key_change(). As these are not inbuilt function these has to implemented in the code.

Using key_swap() function: This function will take input an array and two keys and then swap the values corresponding to these two keys with the help of another variable ($val) and returns the resulting array.

Note: This function will throw an error if both the keys are not present in the array.

Using key_change() function: This function will take input an array and two keys, one old key (already present in the array) and a new key. The function will first store the value corresponding to the old key in to a third variable ($val) and then delete (unset()) the old key and its corresponding value from the array. Then the new key will be added to the array the value stored in the third variable ($val) will be assigned to it and the resulting array will be returned.

Note: This function will return desired output if the new key is not present in the array otherwise if the new key in present in the input array then value of the new key will be lost as the value of the old key will overwrite it. Also, the function will throw an error if the old key is not present in the input array.

Читайте также:  Css фреймворк для приложений

Program: PHP program to reset keys of array element in an array.

Источник

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:

Источник

Как вы переиндексировать массив в 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.

Читайте также:  Template 2

Хорошо, мне хотелось бы думать, что для любой цели, на самом деле вам не нужно было бы изменять массив, чтобы он был основан на 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);

Массив_реверс очень быстрый, и он меняет порядок, когда он меняет направление. Кто-то еще показал мне это давным-давно. Поэтому я не могу смириться с этим. Но это очень просто и быстро.

Источник

How to Reset Array Keys in PHP?

Are you looking for example of how to reset array keys in php. you can understand a concept of php reset array keys starting 0. step by step explain php reset array keys to numeric. In this article, we will implement a reset array keys php starting from 0. Let’s get started with php array_values in php example.

Here, i will give you two examples of how to reset array keys with php and how to reset keys with remove empty values using array_filter function. so let’s see both example with php.

$myArray = [

‘3’ => ‘Mayank’,

‘4’ => ‘Rohit’,

‘2’ => ‘Karan’,

‘7’ => ‘Himmat’

];

$myNewArray = array_values($myArray);

print_r($myNewArray);

?>

Array

(

[0] => Mayank [1] => Rohit [2] => Karan [3] => Himmat

)

$myArray = [

‘3’ => ‘Mayank’,

‘4’ => ‘Rohit’,

‘2’ => ‘Karan’,

‘7’ => ‘Himmat’,

‘6’ => »,

‘9’ => ‘Kiran’,

‘1’ => »

];

$myNewArray = array_values(array_filter($myArray));

print_r($myNewArray);

?>

Array

(

[0] => Mayank [1] => Rohit [2] => Karan [3] => Himmat [4] => Kiran

)

Hardik Savani

I’m a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.

We are Recommending you

Источник

Оцените статью