Php 数组_unique()不使数组唯一

Php 数组_unique()不使数组唯一,php,arrays,Php,Arrays,我根据一个等式生成一个数字数组,然后四舍五入到最接近的100 在这之后,我想消除重复项,array\u unique似乎是这种情况下的自然选择,但没有按预期工作 我创建了一个小样本来演示这一点。 PHP代码如下所示: var_dump($amounts); array_unique($amounts); var_dump($amounts); 其结果是: array(6) { [0]=> float(200) [1]=> float(300) [2]=>

我根据一个等式生成一个数字数组,然后四舍五入到最接近的100

在这之后,我想消除重复项,
array\u unique
似乎是这种情况下的自然选择,但没有按预期工作

我创建了一个小样本来演示这一点。 PHP代码如下所示:

var_dump($amounts);
array_unique($amounts);
var_dump($amounts);
其结果是:

array(6) {
  [0]=>
  float(200)
  [1]=>
  float(300)
  [2]=>
  float(300)
  [3]=>
  float(400)
  [4]=>
  float(500)
  [5]=>
  float(500)
}
array(6) {
  [0]=>
  float(200)
  [1]=>
  float(300)
  [2]=>
  float(300)
  [3]=>
  float(400)
  [4]=>
  float(500)
  [5]=>
  float(500)
}
有人能解释一下这里发生了什么吗?

不通过引用修改数组。您需要捕获返回的值:

$amounts=array\u unique($amounts)

注意:返回数组的键可能不再是连续的。如果要使它们再次相邻,则应使用
array\u值

示例:

$amounts = array(100, 200, 200, 200, 300, 400);
var_dump($amounts);
array(6) {
  [0]=>
  int(100)
  [1]=>
  int(200)
  [2]=>
  int(200)
  [3]=>
  int(200)
  [4]=>
  int(300)
  [5]=>
  int(400)
}

// Make the array unique
$amounts = array_unique($amounts);
var_dump($amounts);
array(4) {
  [0]=>
  int(100)
  [1]=>
  int(200)
  [4]=>
  int(300) // Notice the gap, indexes 2 and 3 don't exist.
  [5]=>
  int(400)
}

// Make the keys contiguous
$amounts = array_values($amounts);
var_dump($amounts);
array(4) {
  [0]=>
  int(100)
  [1]=>
  int(200)
  [2]=>
  int(300)
  [3]=>
  int(400)
}
不通过引用修改数组。您需要捕获返回的值:

$amounts=array\u unique($amounts)

注意:返回数组的键可能不再是连续的。如果要使它们再次相邻,则应使用
array\u值

示例:

$amounts = array(100, 200, 200, 200, 300, 400);
var_dump($amounts);
array(6) {
  [0]=>
  int(100)
  [1]=>
  int(200)
  [2]=>
  int(200)
  [3]=>
  int(200)
  [4]=>
  int(300)
  [5]=>
  int(400)
}

// Make the array unique
$amounts = array_unique($amounts);
var_dump($amounts);
array(4) {
  [0]=>
  int(100)
  [1]=>
  int(200)
  [4]=>
  int(300) // Notice the gap, indexes 2 and 3 don't exist.
  [5]=>
  int(400)
}

// Make the keys contiguous
$amounts = array_values($amounts);
var_dump($amounts);
array(4) {
  [0]=>
  int(100)
  [1]=>
  int(200)
  [2]=>
  int(300)
  [3]=>
  int(400)
}

我真是个新手。我忘记了一件多么简单的事。谢谢。第一班机就足够了,我再过5分钟就接受。谢谢你提供的细节,虽然我是个新手。我忘记了一件多么简单的事。谢谢。第一班机就足够了,我再过5分钟就接受。不过还是谢谢你提供的细节