0
我有以下阵列从数据库中来:PHP单独的数组元素基于共同价值观
$tags = Array
(
[0] => Array
(
[id] => 1
[tag_name] => Testing/EOC
[description] =>
[category] => Category 1
)
[1] => Array
(
[id] => 2
[tag_name] => Technology Tips
[description] =>
[category] => Category 1
)
[2] => Array
(
[id] => 3
[tag_name] => Student Engagement
[description] =>
[category] => Category 1
)
[3] => Array
(
[id] => 4
[tag_name] => Flipped Classroom
[description] =>
[category] => Category 1
)
[4] => Array
(
[id] => 5
[tag_name] => Blended Instruction
[description] =>
[category] => Category 1
)
[5] => Array
(
[id] => 6
[tag_name] => Differentiated Instruction
[description] =>
[category] => Category 1
)
[6] => Array
(
[id] => 7
[tag_name] => Bootcamp
[description] =>
[category] => Category 1
)
[7] => Array
(
[id] => 8
[tag_name] => Mathematical Practices 1
[description] =>
[category] => Category 1
)
[8] => Array
(
[id] => 9
[tag_name] => Mathematical Practices 2
[description] =>
[category] => Category 2
)
[9] => Array
(
[id] => 10
[tag_name] => Mathematical Practices 3
[description] =>
[category] => Category 2
)
[10] => Array
(
[id] => 11
[tag_name] => Mathematical Practices 4
[description] =>
[category] => Category 2
)
[11] => Array
(
[id] => 12
[tag_name] => Mathematical Practices 5
[description] =>
[category] => Category 2
)
[12] => Array
(
[id] => 13
[tag_name] => Mathematical Practices 6
[description] =>
[category] => Category 2
)
[13] => Array
(
[id] => 14
[tag_name] => Mathematical Practices 7
[description] =>
[category] => Category 2
)
[14] => Array
(
[id] => 15
[tag_name] => Mathematical Practices 8
[description] =>
[category] => Category 2
)
[15] => Array
(
[id] => 16
[tag_name] => Pre-Algebra
[description] =>
[category] => Category 3
)
[16] => Array
(
[id] => 17
[tag_name] => Sets and Venn Diagrams
[description] =>
[category] => Category 3
)
)
现在我只是循环,通过像这样:
<ul>
<? foreach($tags as $tag): ?>
<li>
<input type="checkbox" class="tag" name="tags[]" value="<?= $tag['id']; ?>">
<label><?= $tag['tag_name']; ?></label>
</li>
<? endforeach; ?>
</ul>
不过,我真正想要做的是将标签分开,并根据三个不同的类别将它们分为三个部分(可能是他们自己的独立部门)。基本上我想要有三个列,每个都有类别名称作为标题,并在其下面列出适当的标签。不知道如何在循环中实现这一点,并将它们全部保持为同一形式的输入。
$categoryToTag = array();
foreach ($tags as $tag) {
if (!isset($categoryToTag[$tag['category']])) $categoryToTag[$tag['category']] = array();
$categoryToTag[$tag['category']][] = $tag;
}
2遍历的类别和输出标签:
foreach ($categoryToTag as $category => $categoryTags) {
echo 'Category '.$category.' begin';
foreach ($categoryTags as $tag) echo $tag;
}
完美,谢谢 – user2994560