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