回显$ _SESSION数据

时间:2016-07-22 22:09:54

标签: php session mysqli

我在一个数组中有一堆数据已在会话中收集。我可以print_r这个并显示所有内容,但我很难显示产品名称,ID,图像等。

我正在展示使用:

<?php
echo '<pre>';
print_r($_SESSION);
echo '</pre>';
?>

它打印出我需要的所有内容,但不是我要求的格式。所以我知道它正在收集我的数据并将其存储在数组中。我已将数据设置在其他文件中,如下所示:

if (isset($_POST['Submit'])) { 
    $_SESSION['product_img'][] = $_POST['product_img'];
    $_SESSION['product_id'][] = $_POST['product_id'];
    $_SESSION['product_name'][] = $_POST['product_name'];
    $_SESSION['product_price'][] = $_POST['product_price'];
    $_SESSION['product_sku'][] = $_POST['product_sku'];
    $_SESSION['product_description'][] = $_POST['product_description'];
} 

以上是我想输出的所有内容。

2 个答案:

答案 0 :(得分:1)

**您坚持使用提案:$_SESSION['...'][] **

if (isset($_POST['Submit'])) { 
    $_SESSION['product_img'][] = $_POST['product_img'];
    $_SESSION['product_id'][] = $_POST['product_id'];
    $_SESSION['product_name'][] = $_POST['product_name'];
    $_SESSION['product_price'][] = $_POST['product_price'];
    $_SESSION['product_sku'][] = $_POST['product_sku'];
    $_SESSION['product_description'][] = $_POST['product_description'];
} 

并将其格式化为:

foreach($_SESSION as $elements)
{
    foreach($elements as $element) {
        echo $element . '<br />';
    }
}

或使用其他方法:

if (isset($_POST['Submit'])) { 
    $_SESSION['product_img'] = $_POST['product_img'];
    $_SESSION['product_id'] = $_POST['product_id'];
    $_SESSION['product_name'] = $_POST['product_name'];
    $_SESSION['product_price'] = $_POST['product_price'];
    $_SESSION['product_sku'] = $_POST['product_sku'];
    $_SESSION['product_description'] = $_POST['product_description'];
} 

并将其格式化为:

foreach($_SESSION as $element)
{
    echo $element . '<br />';
}

答案 1 :(得分:1)

将此输出为HTML的简单方法是使用foreach循环,该循环遍历数组中的每个项目。

为了简化操作,我建议您更改POST代码,以便每个项目都是一个数组,就像这样。

if (isset($_POST['Submit'])) { 
    $_SESSION['products'][] = array(
        'img' => $_POST['product_img'],
        'id' => $_POST['product_id'],
        'name' => $_POST['product_name'],
        'price' => $_POST['product_price'],
        'sku' => $_POST['product_sku'],
        'description' => $_POST['product_description']
    );
} 

现在,您可以遍历$_SESSION['products']并获取会话中每个产品的信息。例如:

foreach ($_SESSION['products'] as $product) {
    $name = $product['name'];
    $id = $product['id'];
    $price = $product['price'];
    $img = $product['img'];
    $sku = $product['sku'];
    $description = $product['description'];

    echo "<h1>Product: $name</h1>";
    echo "<p>Price: $price | ID: $id</p>";
    echo "<img src='$img'>";
    echo "<p>$description</p>";
    echo "<hr />";
}