我正在生成一个基于等式的数字数组,然后四舍五入到最接近的100。
之后,我想摆脱重复,array_unique
似乎是这种情况下的自然选择,但并不像预期的那样工作。
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)
}
有人能解释一下这里发生了什么吗?
array_unique
不通过引用修改数组。您需要捕获返回值:
$amounts = array_unique($amounts);
注意:返回数组的键可能不再是连续的。如果你想让它们再次连续,那么你应该使用array_values
。
例子:
$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)
}