你如何在 PHP 中重新索引一个数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/591094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:10:54  来源:igfitidea点击:

How do you reindex an array in PHP?

phparraysindexing

提问by meleyal

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] => 
    )

)

回答by Andrew Moore

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:

如果您需要从一个开始,请使用以下命令:

$iOne = array_combine(range(1, count($arr)), array_values($arr));

Here are the manual pages for the functions used:

以下是所用函数的手册页:

回答by Sandra

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 的条目将被删除。)

回答by imagiro

I just found out you can also do 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.

这会进行重新索引,因此您最终不会得到原始数组的副本。

回答by Gumbo

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_valuesto 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 开始,则可以使用上面的算法。

回答by Peter Bailey

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.

好吧,我想无论您的最终目标是什么,您实际上都不需要将数组修改为基于 1 而不是基于 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 ) );
}

回答by Greg

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 ) 

?>

回答by Michael Trausch

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 的索引器时,请考虑一致性——无论是在您的应用程序中还是在您使用的代码中。

回答by Nigel Alderton

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
)

回答by Ionu? Ple?ca

A more elegant solution:

更优雅的解决方案:

$list = array_combine(range(1, count($list)), array_values($list));

回答by Nick

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
        )
)