I have the following array, which I would like to reindex so the keys are reversed (ideally starting at 1):
我有以下数组,我想重新索引,以便键被反转(最好从1开始):
Current array (edit: the array actually looks like this):
当前数组(编辑:数组实际上是这样的):
Array (
[2] => Object
(
[title] => Section
[linked] => 1
)
[1] => Object
(
[title] => Sub-Section
[linked] => 1
)
[0] => Object
(
[title] => Sub-Sub-Section
[linked] =>
)
)
How it should be:
应该是:
Array (
[1] => Object
(
[title] => Section
[linked] => 1
)
[2] => Object
(
[title] => Sub-Section
[linked] => 1
)
[3] => Object
(
[title] => Sub-Sub-Section
[linked] =>
)
)
17 个解决方案
#1
345
If you want to re-index starting to zero, simply do the following:
如果您想要重新索引开始为零,只需执行以下操作:
$iZero = array_values($arr);
If you need it to start at one, then use the following:
如果你需要从1开始,可以使用以下方法:
$iOne = array_combine(range(1, count($arr)), array_values($arr));
Here are the manual pages for the functions used:
以下是使用功能的手册页:
array_values()
- 元素()
array_combine()
- 合二为一()
range()
- range()
#2
46
Here is the best way:
最好的办法是:
# Array
$array = array('tomato', '', 'apple', 'melon', 'cherry', '', '', 'banana');
that returns
返回
Array
(
[0] => tomato
[1] =>
[2] => apple
[3] => melon
[4] => cherry
[5] =>
[6] =>
[7] => banana
)
by doing this
通过这样做
$array = array_values(array_filter($array));
you get this
你得到这个
Array
(
[0] => tomato
[1] => apple
[2] => melon
[3] => cherry
[4] => banana
)
Explanation
解释
array_values()
: Returns the values of the input array and indexes numerically.
array_values():以数值方式返回输入数组和索引的值。
array_filter()
: Filters the elements of an array with a user-defined function (UDF If none is provided, all entries in the input table valued FALSE will be deleted.)
array_filter():使用用户定义函数对数组元素进行筛选(如果不提供UDF,则删除输入表值FALSE中的所有条目)。
#3
7
Why reindexing? Just add 1 to the index:
为什么改变符号?只要在指数上加1:
foreach ($array as $key => $val) {
echo $key + 1, '<br>';
}
Edit After the question has been clarified: You could use the array_values
to reset the index starting at 0. Then you could use the algorithm above if you just want printed elements to start at 1.
问题澄清后进行编辑:可以使用array_values从0开始重置索引。如果你想要打印元素从1开始,那么你可以使用上面的算法。
#4
7
I just found out you can also do a
我刚发现你也可以做a。
array_splice($ar, 0, 0);
That does the re-indexing inplace, so you don't end up with a copy of the original array.
这样就可以重新建立索引,所以最终不会得到原始数组的副本。
#5
5
Well, I would like to think that for whatever your end goal is, you wouldn't actually need to modify the array to be 1-based as opposed to 0-based, but could instead handle it at iteration time like Gumbo posted.
我想,不管你的最终目标是什么,你实际上都不需要修改数组,而不是基于0的数组,而是在像Gumbo这样的迭代时处理它。
However, to answer your question, this function should convert any array into a 1-based version
但是,要回答您的问题,这个函数应该将任何数组转换为基于1的版本
function convertToOneBased( $arr )
{
return array_combine( range( 1, count( $arr ) ), array_values( $arr ) );
}
EDIT
Here's a more reusable/flexible function, should you desire it
如果您需要,这里有一个更可重用/更灵活的功能
$arr = array( 'a', 'b', 'c' );
echo '<pre>';
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 '</pre>';
function reIndexArray( $arr, $startAt=0 )
{
return ( 0 == $startAt )
? array_values( $arr )
: array_combine( range( $startAt, count( $arr ) + ( $startAt - 1 ) ), array_values( $arr ) );
}
#6
4
This will do what you want:
这将做你想做的:
<?php
$array = array(2 => '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 )
?>
#7
4
A more elegant solution:
一个更优雅的解决方案:
$list = array_combine(range(1, count($list)), array_values($list));
#8
3
You may want to consider why you want to use a 1-based array at all. Zero-based arrays (when using non-associative arrays) are pretty standard, and if you're wanting to output to a UI, most would handle the solution by just increasing the integer upon output to the UI.
您可能想要考虑为什么要使用基于1的数组。基于零的数组(当使用非关联数组时)是非常标准的,如果您想要将其输出到UI,大多数人会通过在输出到UI时增加整数来处理解决方案。
Think about consistency—both in your application and in the code you work with—when thinking about 1-based indexers for arrays.
考虑数组的基于1的索引器时,请考虑一致性(在应用程序中和与之一起工作的代码中)。
#9
3
Similar to @monowerker, I needed to reindex an array using an object's key...
与@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);
This resulted in:
这导致了:
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
)
)
#10
2
$tmp = array();
foreach (array_values($array) as $key => $value) {
$tmp[$key+1] = $value;
}
$array = $tmp;
#11
2
You can reindex an array so the new array starts with an index of 1 like this;
你可以重新索引一个数组,这样新的数组的索引从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);
The output from the above is;
上述输出为;
Array
(
[2] => red
[1] => green
[0] => blue
)
Array
(
[1] => red
[2] => green
[3] => blue
)
#12
1
If you are not trying to reorder the array you can just do:
如果你不想重新排序数组,你可以这样做:
$array = array_reverse( $array );
$array = array_reverse( $array );
$array = array_reverse($array);$array = array_reverse($array);
The array_reverse is very fast and it reorders as it reverses. Someone else showed me this a long time ago. So I can't take credit for coming up with it. But it is very simple and fast.
array_reverse非常快,它在反向时重新排序。很久以前有人给我看了这个。所以我不能因为想出这个来而受到称赞。但它非常简单和快速。
#13
1
duplicate removal and reindex an array:
重复删除和重新索引数组:
<?php
$oldArray = array('0'=>'php','1'=>'java','2'=>'','3'=>'asp','4'=>'','5'=>'mysql');
//duplicate removal
$fillteredArray = array_filter($oldArray);
//reindexing actually happens here
$newArray = array_merge($filteredArray);
print_r($newArray);
?>
#14
0
Sorting is just a sort(), reindexing seems a bit silly but if it's needed this will do it. Though not in-place. Use array_walk() if you will do this in a bunch of places, just use a for-key-value loop if this is a one-time operation.
排序只是一种sort(),驯鹿化看起来有点傻,但如果需要的话,可以这样做。虽然不是就地。使用array_walk()如果要在很多地方执行此操作,那么如果这是一次性操作,只需使用for-key-value循环。
<?php
function reindex(&$item, $key, &$reindexedarr) {
$reindexedarr[$key+1] = $item;
}
$arr = Array (2 => 'c', 1 => 'b', 0 => 'a');
sort($arr);
$newarr = Array();
array_walk($arr, reindex, &$newarr);
$arr = $newarr;
print_r($arr); // Array ( [1] => a [2] => b [3] => c )
?>
#15
0
Similar to Nick's contribution, I came to the same solution for reindexing an array, but enhanced the function a little since from PHP version 5.4, it doesn't work because of passing variables by reference. Example reindexing function is then like this using use
keyword closure:
与Nick的贡献类似,我找到了同样的方法来对数组进行驯鹿化,但是对函数进行了一些增强,因为PHP版本5.4,它不能工作,因为通过引用传递变量。例如,驯鹿功能就是这样使用关键字闭包:
function indexArrayByElement($array, $element)
{
$arrayReindexed = [];
array_walk(
$array,
function ($item, $key) use (&$arrayReindexed, $element) {
$arrayReindexed[$item[$element]] = $item;
}
);
return $arrayReindexed;
}
#16
0
Here's my own implementation. Keys in the input array will be renumbered with incrementing keys starting from $start_index.
这是我的自己的实现。输入数组中的键将使用从$start_index开始的递增键重新编号。
function array_reindex($array, $start_index)
{
$array = array_values($array);
$zeros_array = array_fill(0, $start_index, null);
return array_slice(array_merge($zeros_array, $array), $start_index, null, true);
}
#17
-9
If it's OK to make a new array it's this:
如果可以新建一个数组,它是这样的:
$result = array();
foreach ( $array as $key => $val )
$result[ $key+1 ] = $val;
If you need reversal in-place, you need to run backwards so you don't stomp on indexes that you need:
如果你需要在适当的地方反转,你需要向后运行,这样你就不会踩到你需要的索引:
for ( $k = count($array) ; $k-- > 0 ; )
$result[ $k+1 ] = $result[ $k ];
unset( $array[0] ); // remove the "zero" element
#1
345
If you want to re-index starting to zero, simply do the following:
如果您想要重新索引开始为零,只需执行以下操作:
$iZero = array_values($arr);
If you need it to start at one, then use the following:
如果你需要从1开始,可以使用以下方法:
$iOne = array_combine(range(1, count($arr)), array_values($arr));
Here are the manual pages for the functions used:
以下是使用功能的手册页:
array_values()
- 元素()
array_combine()
- 合二为一()
range()
- range()
#2
46
Here is the best way:
最好的办法是:
# Array
$array = array('tomato', '', 'apple', 'melon', 'cherry', '', '', 'banana');
that returns
返回
Array
(
[0] => tomato
[1] =>
[2] => apple
[3] => melon
[4] => cherry
[5] =>
[6] =>
[7] => banana
)
by doing this
通过这样做
$array = array_values(array_filter($array));
you get this
你得到这个
Array
(
[0] => tomato
[1] => apple
[2] => melon
[3] => cherry
[4] => banana
)
Explanation
解释
array_values()
: Returns the values of the input array and indexes numerically.
array_values():以数值方式返回输入数组和索引的值。
array_filter()
: Filters the elements of an array with a user-defined function (UDF If none is provided, all entries in the input table valued FALSE will be deleted.)
array_filter():使用用户定义函数对数组元素进行筛选(如果不提供UDF,则删除输入表值FALSE中的所有条目)。
#3
7
Why reindexing? Just add 1 to the index:
为什么改变符号?只要在指数上加1:
foreach ($array as $key => $val) {
echo $key + 1, '<br>';
}
Edit After the question has been clarified: You could use the array_values
to reset the index starting at 0. Then you could use the algorithm above if you just want printed elements to start at 1.
问题澄清后进行编辑:可以使用array_values从0开始重置索引。如果你想要打印元素从1开始,那么你可以使用上面的算法。
#4
7
I just found out you can also do a
我刚发现你也可以做a。
array_splice($ar, 0, 0);
That does the re-indexing inplace, so you don't end up with a copy of the original array.
这样就可以重新建立索引,所以最终不会得到原始数组的副本。
#5
5
Well, I would like to think that for whatever your end goal is, you wouldn't actually need to modify the array to be 1-based as opposed to 0-based, but could instead handle it at iteration time like Gumbo posted.
我想,不管你的最终目标是什么,你实际上都不需要修改数组,而不是基于0的数组,而是在像Gumbo这样的迭代时处理它。
However, to answer your question, this function should convert any array into a 1-based version
但是,要回答您的问题,这个函数应该将任何数组转换为基于1的版本
function convertToOneBased( $arr )
{
return array_combine( range( 1, count( $arr ) ), array_values( $arr ) );
}
EDIT
Here's a more reusable/flexible function, should you desire it
如果您需要,这里有一个更可重用/更灵活的功能
$arr = array( 'a', 'b', 'c' );
echo '<pre>';
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 '</pre>';
function reIndexArray( $arr, $startAt=0 )
{
return ( 0 == $startAt )
? array_values( $arr )
: array_combine( range( $startAt, count( $arr ) + ( $startAt - 1 ) ), array_values( $arr ) );
}
#6
4
This will do what you want:
这将做你想做的:
<?php
$array = array(2 => '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 )
?>
#7
4
A more elegant solution:
一个更优雅的解决方案:
$list = array_combine(range(1, count($list)), array_values($list));
#8
3
You may want to consider why you want to use a 1-based array at all. Zero-based arrays (when using non-associative arrays) are pretty standard, and if you're wanting to output to a UI, most would handle the solution by just increasing the integer upon output to the UI.
您可能想要考虑为什么要使用基于1的数组。基于零的数组(当使用非关联数组时)是非常标准的,如果您想要将其输出到UI,大多数人会通过在输出到UI时增加整数来处理解决方案。
Think about consistency—both in your application and in the code you work with—when thinking about 1-based indexers for arrays.
考虑数组的基于1的索引器时,请考虑一致性(在应用程序中和与之一起工作的代码中)。
#9
3
Similar to @monowerker, I needed to reindex an array using an object's key...
与@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);
This resulted in:
这导致了:
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
)
)
#10
2
$tmp = array();
foreach (array_values($array) as $key => $value) {
$tmp[$key+1] = $value;
}
$array = $tmp;
#11
2
You can reindex an array so the new array starts with an index of 1 like this;
你可以重新索引一个数组,这样新的数组的索引从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);
The output from the above is;
上述输出为;
Array
(
[2] => red
[1] => green
[0] => blue
)
Array
(
[1] => red
[2] => green
[3] => blue
)
#12
1
If you are not trying to reorder the array you can just do:
如果你不想重新排序数组,你可以这样做:
$array = array_reverse( $array );
$array = array_reverse( $array );
$array = array_reverse($array);$array = array_reverse($array);
The array_reverse is very fast and it reorders as it reverses. Someone else showed me this a long time ago. So I can't take credit for coming up with it. But it is very simple and fast.
array_reverse非常快,它在反向时重新排序。很久以前有人给我看了这个。所以我不能因为想出这个来而受到称赞。但它非常简单和快速。
#13
1
duplicate removal and reindex an array:
重复删除和重新索引数组:
<?php
$oldArray = array('0'=>'php','1'=>'java','2'=>'','3'=>'asp','4'=>'','5'=>'mysql');
//duplicate removal
$fillteredArray = array_filter($oldArray);
//reindexing actually happens here
$newArray = array_merge($filteredArray);
print_r($newArray);
?>
#14
0
Sorting is just a sort(), reindexing seems a bit silly but if it's needed this will do it. Though not in-place. Use array_walk() if you will do this in a bunch of places, just use a for-key-value loop if this is a one-time operation.
排序只是一种sort(),驯鹿化看起来有点傻,但如果需要的话,可以这样做。虽然不是就地。使用array_walk()如果要在很多地方执行此操作,那么如果这是一次性操作,只需使用for-key-value循环。
<?php
function reindex(&$item, $key, &$reindexedarr) {
$reindexedarr[$key+1] = $item;
}
$arr = Array (2 => 'c', 1 => 'b', 0 => 'a');
sort($arr);
$newarr = Array();
array_walk($arr, reindex, &$newarr);
$arr = $newarr;
print_r($arr); // Array ( [1] => a [2] => b [3] => c )
?>
#15
0
Similar to Nick's contribution, I came to the same solution for reindexing an array, but enhanced the function a little since from PHP version 5.4, it doesn't work because of passing variables by reference. Example reindexing function is then like this using use
keyword closure:
与Nick的贡献类似,我找到了同样的方法来对数组进行驯鹿化,但是对函数进行了一些增强,因为PHP版本5.4,它不能工作,因为通过引用传递变量。例如,驯鹿功能就是这样使用关键字闭包:
function indexArrayByElement($array, $element)
{
$arrayReindexed = [];
array_walk(
$array,
function ($item, $key) use (&$arrayReindexed, $element) {
$arrayReindexed[$item[$element]] = $item;
}
);
return $arrayReindexed;
}
#16
0
Here's my own implementation. Keys in the input array will be renumbered with incrementing keys starting from $start_index.
这是我的自己的实现。输入数组中的键将使用从$start_index开始的递增键重新编号。
function array_reindex($array, $start_index)
{
$array = array_values($array);
$zeros_array = array_fill(0, $start_index, null);
return array_slice(array_merge($zeros_array, $array), $start_index, null, true);
}
#17
-9
If it's OK to make a new array it's this:
如果可以新建一个数组,它是这样的:
$result = array();
foreach ( $array as $key => $val )
$result[ $key+1 ] = $val;
If you need reversal in-place, you need to run backwards so you don't stomp on indexes that you need:
如果你需要在适当的地方反转,你需要向后运行,这样你就不会踩到你需要的索引:
for ( $k = count($array) ; $k-- > 0 ; )
$result[ $k+1 ] = $result[ $k ];
unset( $array[0] ); // remove the "zero" element