PHP 对齐数组键值

发布于 2024-10-09 03:15:56 字数 463 浏览 1 评论 0原文

我在 Google 上搜索了两天,并尝试查看 PHP 手册,但我仍然不记得那个对齐 PHP 数组键值的函数。

我正在寻找的是接受这个的函数:

Array
(
    [0] => 1
    [3] => 2
    [4] => 3
    [7] => 4
    [9] => 5
)

并将其转换为:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

基本上,数组首先按键排序(附加到它们的值与它们保持一致),然后所有键都设置为所有计数数字,连续,不跳过任何数字(0,1,2,3,4,5,6,7,8,9...)。几个月前我看到它与 ksort() 一起使用,但无法记住或找到这个难以捉摸的函数。

I've Googled it for two days, and tried looking at the PHP manual, and I still can't remember that function that aligns the key values for PHP arrays.

All I'm looking for is the function that takes this:

Array
(
    [0] => 1
    [3] => 2
    [4] => 3
    [7] => 4
    [9] => 5
)

And converts it into this:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Basically, the array is first sorted by key (their values attached to them stay with them), then all the keys are set to all the counting numbers, consecutively, without skipping any number (0,1,2,3,4,5,6,7,8,9...). I saw it being used with ksort() a few months ago, and can't see to remember or find this elusive function.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

北恋 2024-10-16 03:15:56

好吧,你看,这个很难,因为 PHP 数组函数页面上的一般描述并没有说这个函数可以实现你正在寻找的功能。

但是您可以使用 ksort() 对数组进行排序,然后使用 array_values() 。来自 PHP 手册的页面:

array_values() 返回输入数组中的所有值,并以数字方式对数组进行索引。

Well, you see, this one is hard, because the general description on the PHP array functions page does not say that this function does what you're looking for.

But you can sort the array using ksort(), and then use this: array_values() . From the page from the PHP manual:

array_values() returns all the values from the input array and indexes numerically the array.

如果没有你 2024-10-16 03:15:56

您可以使用 array_merge

$array = array_merge($array);

它将用数字键重新索引值。

更新:按照@LostInTheCode 的回答可能更具描述性。

You can use array_merge:

$array = array_merge($array);

It will reindex values with numeric keys.

Update: Using array_values as proposed in @LostInTheCode's answer is probably more descriptive.

枕梦 2024-10-16 03:15:56
function array_reset_index_keys($array)
{
    $return = array();foreach($array as $k => $v){$return[] = $v;}return $return;
}

然后像常规函数一样使用,应该重新索引数组,

您还可以使用本机函数,例如 array_values ,它将数组的值返回到单维数组中,从而使其被重新索引。

function array_reset_index_keys($array)
{
    $return = array();foreach($array as $k => $v){$return[] = $v;}return $return;
}

And then use like a regular function, should re index the array

you can also use native functions such as array_values which returns the values of an array into a single dimension array, causing it to be re indexed .

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文