从php数组创建下拉列表


creating dropdown from php array

我有这样的数组:

Array (
    [0] => Array(             
        [attribute_name] => Brand             
        [attribute_value] => Lee         
    )      
    [1] => Array(
         [attribute_name] => Brand  
         [attribute_value] => Levis         
    )      
    [2] => Array( 
        [attribute_name] => Brand    
        [attribute_value] => Raymond         
    )      
    [3] => Array( 
        [attribute_name] => Fabric 
        [attribute_value] => Cotton         
    )   
    [4] => Array(
        [attribute_name] => Fabric  
        [attribute_value] => Linen         
    )  
)

我想从这个数组中创建两个下拉列表,一个用于Brand,它应该有三个选项,另一个用于应该有两个选项的fabric

我可以简单地检查attribute_namebrandfabric,但这不是静态的——可以有任何东西代替brandfabric

我尝试了很多东西,但都没有成功。请帮我做这件事。提前谢谢。

$filteredArray = array();
foreach ($array as $key => $value) {
    if ($key === 'Brand' || $key === 'Fabric') {
        array_push($filteredArray, $value);
    }
}

$filteredArray现在只包含Brand和Fabric。

对于这种结构,必须首先从数据中创建一个分组数组。因此,反过来,它们将更容易管理。首先,通过使用循环,使用属性名称作为键,推送值,对所有这些值进行分组。看起来像这样:

// grouping
$grouped = array();
foreach($array as $values) {
    $grouped[$values['attribute_name']][] = $values['attribute_value'];
}

这个循环将创建这样的结构:

Array
(
    [Brand] => Array
        (
            [0] => Lee
            [1] => Levis
            [2] => Raymond
        )
    [Fabric] => Array
        (
            [0] => Cotton
            [1] => Linen
        )
)

分组后。然后是演示:

用这个作为一个想法:

<form method="POST">
<?php foreach($grouped as $label => $values): ?>
    <label><?php echo $label; ?></label>
    <select name="select_values[<?php echo $label; ?>]">
        <?php foreach($values as $value): ?>
        <option value="<?php echo $value; ?>"><?php echo $value; ?></option>
        <?php endforeach; ?>
    </select><br/><br/>
<?php endforeach; ?>
<br/><input type="submit" />
</form>

然后,一旦你提交了表格,就像往常一样处理它。给它分配一些变量。

if(!empty($_POST['select_values'])) {
    $selected = $_POST['select_values'];
    echo '<pre>', print_r($selected, 1), '</pre>';
}

在做出选择后,情况会是这样的:

Array
(
    [Brand] => Lee
    [Fabric] => Cotton
)