0

I have an array of data similar to the following:

$array[0] = array('key1' => 'value1a','key2' => 'value2a','key3' => 'value3a');
$array[1] = array('key1' => 'value1a','key2' => 'value2b','key3' => 'value3b');
$array[2] = array('key1' => 'value1b','key2' => 'value2b','key3' => 'value3c');
$array[3] = array('key1' => 'value1c','key2' => 'value2c','key3' => 'value3c');

I need to use this data to create a set of dropdown lists based on each key. However, I want to remove the duplicates, so that each dropdown list only shows the unique values.

I started with:

<select>
<?php   
    foreach($array AS $arr)
        {
            print "<option>".$arr['key1']."</option>";
        };
?>
</select></br>

as expected, this gave me 4 entries, two of which were the same.

So I tried:

<select>
<?php   
    foreach(array_unique($array) AS $arr)
        {
            print "<option>".$arr['key1']."</option>";
        };
?>
</select></br>

and also:

<select>
    <?php   
        $arr = array_unique($array);
        foreach ($arr AS $a)
            {
                print "<option>".$a['key1']."</option>";
            };
    ?>
</select></br>  

But these only give me one item (value1a). On closer inspection I see that it has actually generated a string of errors:

Notice:  Array to string conversion in C:\Apache24\htdocs\TEST\test29.php on line 39

But I can't figure out why this is, or how to fix it to get the list I want?

How can I get a list of just the unique entries?

IGGt
  • 2,627
  • 10
  • 42
  • 63
  • 1
    `$array` is multidimensional array. Do `print_r($array);` and you will see what I am talking about. – Glavić Sep 04 '13 at 08:12
  • 1
    This example could help you . http://stackoverflow.com/questions/3598298/php-remove-duplicate-values-from-multidimensional-array – Piyush Aggarwal Sep 04 '13 at 08:42

1 Answers1

3

Since PHP 5.5, you can use array_column function:

    foreach(array_unique(array_column($array, 'key1')) AS $arr)
    {
        print "<option>".$arr."</option>";
    };

but, it you have older version, you can do:

    foreach(array_unique(array_map(function($rgItem)
    {
       return $rgItem['key1'];
    }, $array)) AS $arr)
    {
        print "<option>".$arr."</option>";
    };
Alma Do
  • 37,009
  • 9
  • 76
  • 105
  • cheers for that, I'm currently running PHP 5.4, but the second option you gave seems to work a treat. – IGGt Sep 04 '13 at 11:05