php - array_unique 是否开始新的数组索引号?

标签 php arrays

如果我有一个使用整数作为索引的数组。 (1、2、3 等)。当我在其上使用 array_unique 函数时,新数组值是否会使用从 1 开始的新索引存储?或者这个新数组是否使用与前一个数组相同的索引?

谢谢,任何帮助将不胜感激。

最佳答案

它确实使用与 array_unique() 相同的索引......保留 key ..

来自PHP Docs ..

Note that keys are preserved. array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys. It does not mean that the key of the first related value from the unsorted array will be kept.


Nope. I want to put them into a new array starting from index 1. Any way to do that then?

数组索引以 0 作为默认索引开始!下面的代码创建一个索引从 1 开始的新数组。

<?php
$arr = array(1,2,3);
foreach($arr as $k=>$v)
{
    $new_arr[++$k]=$v;
}
print_r($new_arr);

输出:

Array
(
    [1] => 1
    [2] => 2
    [3] => 3
)

关于php - array_unique 是否开始新的数组索引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23166005/

相关文章:

php - 网站被黑,如何使用 SED/GREP 删除恶意代码

php - 具有可扩展段长度的 laravel 路由

php - 处理两个多维数组并跳过最终输出中共享值的数组

android - 如何从 Firebase 获取字符串列表来填充 Spinner

c++ - 创建指向结构的指针数组 - C++

php while循环变量每三个div

php - MySQL bind_param 向表写入 NULL

javascript - 根据属性值将对象数组中的属性合并到另一个对象数组中 lodash

C - 按字母顺序排序数组错误

c++ - 动态数组和重复值