在PHP中处理多维数组



我有一个像这样的$row数组值。

    Array
    (
            [123] => Array
                (
                    [0] => Array
                        (
                            [author_name] => A1
                            [book_name] => A1B1
                            [rating] => 5
                        )
                    [1] => Array
                        (
                            [author_name] => A1
                            [book_name] => A1B2
                            [rating] => 5.5
                        )
                    [2] => Array
                        (
                            [author_name] => A1
                            [book_name] => A1B3
                            [rating] => 5.7
                        )
                )

                [456] => Array
                (
                    [0] => Array
                        (
                            [author_name] => A2
                            [book_name] => A2B1
                            [rating] => 7
                        )
                  )     
    )         

我需要像这样显示上面的数组值。

    Author Code         Author Name     Book Name       Rating
    123                 A1              A1B1            5   
                                        AlB2            5.5
                                        A1B3            5.7
    456                 A2              A2B1            7       

我是数组概念的新手,现在我能够单独获取数组。任何php代码都会有很大的帮助。

我不知道还有什么其他方法(或选项)可以打印这样的东西,但是,您也可以重新构建它。考虑这个例子:

<?php
$original_values = array(
    123 => array(
        array('author_name' => 'A1', 'book_name' => 'A1B1', 'rating' => 5),
        array('author_name' => 'A1', 'book_name' => 'A1B3', 'rating' => 5.5),
        array('author_name' => 'A1', 'book_name' => 'A1B1', 'rating' => 5.7),
    ),
    456 => array(
        array('author_name' => 'A2', 'book_name' => 'A2B1', 'rating' => 7),
    ),
);
$formatted_values = array();
foreach($original_values as $id => $array1) {
    foreach($array1 as $index => $value) {
        $formatted_values[$id][$value['author_name']][] = array('name' => $value['book_name'], 'rating' => $value['rating']);
    }
}
?>
<table cellpadding="10">
    <thead><tr><th>Author Code</th><th>Book Name</th><th>Book Name</th><th>Rating</th></tr></thead>
    <tbody>
    <?php foreach($formatted_values as $author_code => $value): ?>
        <tr valign="top">
            <td><?php echo $author_code; ?></td>
            <?php foreach($value as $author_name => $books): ?>
                <td><?php echo $author_name; ?></td>
                <td><?php foreach($books as $book_info): ?><?php echo $book_info['name']; ?><br/><?php endforeach; ?></td>
                <td><?php foreach($books as $book_info): ?><?php echo $book_info['rating']; ?><br/><?php endforeach; ?></td>
            <?php endforeach; ?>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>

相关内容

  • 没有找到相关文章

最新更新