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?

2
  • 1
    $array is multidimensional array. Do print_r($array); and you will see what I am talking about. Commented Sep 4, 2013 at 8:12
  • 1
    This example could help you . stackoverflow.com/questions/3598298/… Commented Sep 4, 2013 at 8:42

1 Answer 1

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>";
    };
Sign up to request clarification or add additional context in comments.

1 Comment

cheers for that, I'm currently running PHP 5.4, but the second option you gave seems to work a treat.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.