Remove duplicate elements in Array

6

I am getting an array by JSON , and using array_unique to remove duplicate values, however, it is displaying the following error: <b>Notice</b>: Array to string conversion in <b>/var/www/html/.... </b> on line <b>10</b><br />"

In line 10 is just the array_unique .

I tried several ways, but I can not remove these duplicate values.

Can anyone help me?

Note: data sent by JSON is being received correctly.

$dados = json_decode(($_POST['dados']));
$dados_arr = array_unique($dados); //linha 10
print_r($dados_arr);
    
asked by anonymous 26.08.2015 / 17:08

1 answer

4

The PHP Manual does not detail this in the Portuguese version of the array_unique function, but in the English version, it shows that this function has a second parameter.

See the "skeleton" of this function - taken from PHP Manual, array_unique, in English :

array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

The array_unique function internally uses a comparison method, which by default values are treated as strings , and so the error is generated.

So you have to change this form of comparison. Instead of SORT_STRING we will use SORT_REGULAR .

Example:

$dados = json_decode(($_POST['dados']));
$dados_arr = array_unique($dados, SORT_REGULAR); //linha 10
print_r($dados_arr);

By adding the constant SORT_REGULAR to the second parameter of array_unique , it is possible to work with other values, regardless of the type.

We can even use SORT_REGULAR to make a collection of unique objects .

For more information, see the possible flags that can be used with array_unique .

  • SORT_REGULAR - compare items normally (does not change types)
  • SORT_NUMERIC - compare items numerically
  • SORT_STRING - compare items as strings
  • SORT_LOCALE_STRING - compares items as strings, based on current location.
26.08.2015 / 17:27