我有这样的数组:
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_name
是brand
还是fabric
,但这不是一成不变的,可以有任何内容,而不是brand
和fabric
。
我尝试了很多东西但没有奏效。请帮我这样做。提前谢谢。
答案 0 :(得分:2)
$filteredArray = array();
foreach ($array as $key => $value) {
if ($key === 'Brand' || $key === 'Fabric') {
array_push($filteredArray, $value);
}
}
$ filteredArray现在只包含Brand和Fabric。
答案 1 :(得分:0)
对于这种结构,您必须首先从数据中创建分组数组。反过来,他们会更容易管理。首先,使用循环对所有这些进行分组,使用属性名称作为键,推送值。会看起来像这样:
// 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
)