简体   繁体   中英

php - get only unique values from array into dropdown list

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?

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>";
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM