PHP array_unique的奇怪行为 [英] strange behavior of php array_unique
问题描述
我使用code的遵循和平输出数组:
I'm using following peace of code to output an array:
echo "======output without array_unique=====";
var_dump($selected);
echo "=====output with array_unique=====";
var_dump(array_unique($selected));die;
和输出是:
======output without array_unique=====
array
0 =>
array
'uri' => string 'http://localhost/conferences/tags/0caf4c990e0a385156b33fee58e7e3fb' (length=63)
'tag' => string '1' (length=1)
'weight' => float 4
'selected' => string 'select' (length=6)
1 =>
array
'uri' => string 'http://localhost/conferences/tags/0caf4c990e0a385156b33fee58e7e3fb' (length=63)
'tag' => string '1' (length=1)
'weight' => float 4
'selected' => string 'select' (length=6)
2 =>
array
'uri' => string 'http://localhost/conferences/tags/ffc709d5131f752df8aae22d7da4240f' (length=63)
'tag' => string '2' (length=1)
'weight' => float 4
'selected' => string '' (length=0)
3 =>
array
'uri' => string 'http://localhost/conferences/tags/035c60c7f090412cc905cee008fbeba8' (length=63)
'tag' => string '3' (length=1)
'weight' => float 0
'selected' => string '' (length=0)
4 =>
array
'uri' => string 'http://localhost/conferences/tags/4137dbc16ef1a2079eb6cacb62dd8521' (length=63)
'tag' => string '4' (length=1)
'weight' => float 0
'selected' => string '' (length=0)
=====output with array_unique=====
array
0 =>
array
'uri' => string 'http://localhost/conferences/tags/0caf4c990e0a385156b33fee58e7e3fb' (length=63)
'tag' => string '1' (length=1)
'weight' => float 4
'selected' => string 'select' (length=6)
有人能解释我,为什么我得到的数组从array_unique只有一个元素?
Can someone explain me, why i get array with only one element from the array_unique?
推荐答案
的数组元素转换为字符串比较 - 这里是从的对于array_unique 手册页
The array elements are cast to strings for comparison - here's the relevant snippet from the manual page for array_unique
注:有两个因素被认为是
等于当且仅当(字符串)$ elem1
===(字符串)$ elem2时。在话:当字符串重新presentation是一样的。
第一元件将被使用。
Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same. The first element will be used.
一旦你的数组元素转换为字符串,它们只是有值阵列,当然,这使得每一个元素看起来是一样的,你风与刚才的第一个元素。
Once your array elements are cast to strings, they simply have the value "Array", which of course makes every element look the same, and you wind up with just the first element.
这里有一种方法,你可以从像您这样的一个数组
Here's one way you could remove duplicates from an array like yours
$seen=array();
foreach($myarray as $key=>$val)
{
if (isset($seen[$val['uri']])
{
//remove dupe
unset($myarray[$key]);
}
else
{
//remember this
$seen[$val['uri']]=$key;
}
}
unset($seen); //don't need this any more
这篇关于PHP array_unique的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!