1
以下二维数组存储多个图像的信息(1.Book包含图像,2.包含图像的书的作者,3.图像的名称,4.Image ID):检索并显示存储在多维数组中的数据
$images = array(array('book_name'=>"BookA", 'author_name'=>"AuthorA",
'image_name'=>"ImageA", 'image_id'=>1),
array('book_name'=>"BookA",'author_name'=>"AuthorB",
'image_name'=>"ImageA", 'image_id'=>1),
array('book_name'=>"BookA",'author_name'=>"AuthorA",
'image_name'=>"ImageB", 'image_id'=>2),
array('book_name'=>"BookA", 'author_name'=>"AuthorB",
'image_name'=>"ImageB", 'image_id'=>2),
array('book_name'=>"BookB", 'author_name'=>"AuthorA",
'image_name'=>"ImageB", 'image_id'=>2));
一本书可以有多个作者。 作者可以与几本书相关联。 图像可以包含在几本书中。
我想创建一个HTML表具有以下的列:
- 书(S) - 现场列出了所有包含特定图像的书籍
- 作者(S) - 现场列出了所有所有包含该特定图像
- 图片名称的书籍的作者 - 字段包含
我目前使用下面的代码,图像的名称:
<?php function transform($images) {
$result = array();
foreach($images as $key => $image) {
$image_id = $image['image_id'];
if (!isset($result[$image_id])) {
$result[$image_id] = array(
'author_name' => array(),
'book_name' => $image['book_name'],
'image_id' => $image['image_id'],
'image_name' => $image['image_name']
);
}
$result[$image_id]['author_name'] = array_merge($result[$image_id]['author_name'],
array(($image['author_name'])));
}
foreach($result as $key => $data) {
$uniqueauthors = array_unique($result[$key]['author_name']);
$result[$key]['author_name'] = implode('; ', $uniqueauthors);
}
return $result;
}
$images = transform($images);?>
我的HTML代码来创建表:
<table>
<tr><th>Book(s)</th>
<th>Author(s)</th>
<th>Image Name</th>
</tr>
<?php foreach ($images as $image): ?>
<tr>
<td><?php htmlout($image['book_name']); ?></td>
<td><?php htmlout($image['author_name']); ?></td>
<td><?php htmlout($image['image_name']); ?></td>
</tr>
<?php endforeach; ?>
</table>
结果表:
Book(s) | Author(s) | Image Name
BookA AuthorA;AuthorB ImageA
BookA AuthorA;AuthorB ImageB
所需的表:
Book(s) | Author(s) | Image Name
BookA AuthorA;AuthorB ImageA
BookA;BookB AuthorA;AuthorB ImageB
问题: 钍是代码正确输出(2.)包含所述图像的所有书籍的所有作者列表和(3.)图像名称。但是,它不会根据需要输出(3.):它仅输出包含有问题图像的第一个book_name(BookA),而不是包含图像的所有书籍(BookA; BookB)的列表。如何获取一个包含3列的HTML表格(1.)列出包含所涉及图像的所有书籍,(2)列出包含所涉及图像的书籍的所有作者, (3.)包含有问题的图像的名称。 非常感谢!
是的,我忘记了foreach循环中的书籍。谢谢戴尔,你的解决方案的作品! – user1894374