Home  >  Article  >  php教程  >  php array_unique 处理后json_encode注意事项

php array_unique 处理后json_encode注意事项

WBOY
WBOYOriginal
2016-06-08 17:25:441061browse

php教程 array_unique 处理后json_encode注意事项

array_unique() 先将值作为字符串排序,然后对每个值只保留第一个遇到的键名,接着忽略所有后面的键名。这并不意味着在未排序的 array 中同一个值的第一个出现的键名会被保留。

例如:array_unique(array(1, 1, 2)); ]
他的结果是
array(2) {
[0]=>
int(1)
[2]=>
int(2)
}

array_unique() 函数移除数组中的重复的值,并返回结果数组。

当几个数组元素的值相等时,只保留第一个元素,其他的元素被删除。

返回的数组中键名不变。


这就不是numeric数组了,直接做json_encode,会输出一个json对象,而不是数组
{"0":1,"2":2}

如果这时候页面上js需要的是[1,2]这种数组数据格式,就有可能会产生错误

此时应该在array_unique之后,在做一个array_values
这样:array_values(array_unique(array(1, 1, 2)));

结果就是[1,2]

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn