array_uniquee php,PHP array_unique的奇怪行为

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;

And the output is:

======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)

Can someone explain me, why i get array with only one element from the array_unique?

解决方案

The array elements are cast to strings for comparison - here's the relevant snippet from the manual page for array_unique

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值