从数据库打印二维数组


Print 2 dimensional array from DB

我还是一个新程序员。这不是我的日常工作,但我知道足够危险。我已经成功地将嵌套数组插入数据库,但我不知道如何让它正确显示。这是结帐过程中订购的商品列表。

这是回显的数组:

Array
(
    [products] => Array
        (
            [0] => Array
                (
                    [name] => m10x1-5-001 IVB bolt
                    [code] => m10x1-5-001
                    [qty] => 1
                    [price] => 37.00
                    [image] => m10x1-5-001-S.jpg
                    [description] => This is a short description of my item.
                )
            [1] => Array
                (
                    [name] => AA02-015-021 IVB bolt
                    [code] => AA02-015-021
                    [qty] => 1
                    [price] => 39.00
                    [image] => m10x1-5-001-S.jpg
                    [description] => I'm a classic bolt.
                )
        )
)

我需要以可读的格式对此进行回显,因为它正在订单管理页面上进行。它被序列化存储在 mysql 的"产品"字段中,这是我不起作用的起始代码:

if ($result->num_rows > 0) {
echo "<table border='1'><tr><th>ID</th><th>header1</th><th>header2:</th><th>Items:</th></tr>";
while($row = $result->fetch_assoc()) {
    $decrypted = decrypt(base64_decode($row["number"]), ENCRYPTION_KEY);
    $decrypted2 = decrypt(base64_decode($row["cvv"]), ENCRYPTION_KEY);
    echo "<tr><td>".$row["id"]."</td><td>".$decrypted."</td><td>".$decrypted2."</td><td>";
   $listitems = base64_decode(unserialize($row["products"]));
        foreach($listitems as $item)
        {
           echo $item['name'] . $item['code'] . $item['qty'] . $item['price'] . $item['image'] . $item['description'] ;
        }

   echo "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}

我知道这段代码还没有提到数组的嵌套性质。新手需要一点帮助。

对于格式化的输出,您可以打印一个 HTML 表格:

$listitems = base64_decode(unserialize($row["products"]));
$output = '<table>
    <tr>
        <th>Name</th>
        <th>Code</th>
        <th>Quantity</th>
        <th>Price</th>
        <th>Image</th>
        <th>Description</th>
    </tr>
';
foreach($listitems as $item)
{
    $output .= '<tr>
        <td>' . $item['name'] . '</td>
        <td>' . $item['code'] . '</td>
        <td>' . $item['qty'] . '</td>
        <td>' . $item['price'] . '</td>
        <td>' . $item['image'] . '</td>
        <td>' . $item['description'] . '</td>
    </tr>';
}
$output .= '</table>';
echo $output;