我无法将数组转换为正确嵌套的HTML。假设我有一个包含以下示例值的数组 -
An, Author---Some Book
Another, Author---A Book
Another, Author---Another Book
Be, Author---Book 1
Be, Author---Book 2
No, Author---Book 1
如何将其转换为有组织的HTML,如
<div>
<div class="letter">A</div>
<div>
<div class="author">An, Author</div>
<div class="title">Some Book</div>
</div>
<div>
<div class="author">Another, Author</div>
<div class="title">A Book</div>
<div class="title">Another Book</div>
</div>
<div>
<div>
<div class="letter">B</div>
<div>
<div class="author">Be, Author</div>
<div class="title">Book 1</div>
<div class="title">Book 2</div>
</div>
<div>
<div>
<div class="letter">N</div>
<div>
<div class="author">No, Author</div>
<div class="title">Book 1</div>
</div>
<div>
我对PHP没有任何问题,我只是不确定如何组织数据。在将数据重新拉回之前,分成三个不同的数组(字母,作者,书籍)?但那我将如何关联这些书(Letter-&gt; Author-&gt; Book)?
感谢任何想法。
答案 0 :(得分:2)
假设您的数组已经按照示例排序:
for ($i = 0; $i < count($array); $i++) {
$parts = explode("---", $array[$i]);
$author = $parts[0];
$book = $parts[1];
$letter = substr($author, 0, 1);
if (!isset($last_author) || $last_author != $author) {
if ($i > 0 && $last_letter != $letter) {
echo "\t</div>\n";
echo "</div>\n";
} else if ($i > 0) {
echo "\t</div>\n";
}
if (!isset($last_letter) || $last_letter != $letter) {
echo "<div>\n";
echo "\t" . '<div class="letter">' . strtoupper($letter) . '</div>' . "\n";
$last_letter = $letter;
}
echo "\t<div>\n";
echo "\t\t" . '<div class="author">' . $author . '</div>' . "\n";
echo "\t\t" . '<div class="title">' . $book . '</div>' . "\n";
$last_author = $author;
} else {
echo "\t\t" . '<div class="title">' . $book . '</div>' . "\n";
}
}
if (count($array) > 0) echo "\t</div>\n</div>";
样本数组的输出:
<div>
<div class="letter">A</div>
<div>
<div class="author">An, Author</div>
<div class="title">Some Book</div>
</div>
<div>
<div class="author">Another, Author</div>
<div class="title">A Book</div>
<div class="title">Another Book</div>
</div>
</div>
<div>
<div class="letter">B</div>
<div>
<div class="author">Be, Author</div>
<div class="title">Book 1</div>
<div class="title">Book 2</div>
</div>
</div>
<div>
<div class="letter">N</div>
<div>
<div class="author">No, Author</div>
<div class="title">Book 1</div>
</div>
</div>
答案 1 :(得分:0)
您还可以生成一个多维数组,可能需要更少的代码来呈现:
$new = array();
for ($i = 0; $i < count($array); $i++) {
$parts = explode("---", $array[$i]);
$author = $parts[0];
$book = $parts[1];
$letter = substr($author, 0, 1);
$new[$letter][$author][] = $book;
}
foreach ($new as $letter => $authors) {
foreach ($authors as $author => $books) {
foreach ($books as $book) {
}
}
}
答案 2 :(得分:0)
你有div汤,但你解析你的阵列。
尝试使用列表输出有意义和语义的内容。