php保存数组值

时间:2016-06-02 13:05:57

标签: php session

我需要在$_SESSION['lastViewedProductsList']中保存过去10个已浏览的产品,因此我尝试使用下面的代码,但在这种情况下,$product仅保留最后$title = $node->title; $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $img = $node->uc_product_image['und'][0]['filename']; $product = array('title' => $title, 'url' => $url, 'img' => $img); if (!isset($_SESSION['lastViewedProductsList'])) { $_SESSION['lastViewedProductsList'] = $product; } else { $_SESSION['lastViewedProductsList'] = $product; }

<xsl:value-of select="/CETOLReport
                      /PrtAsm[@Type=$PrtAsmType and @CadName=$CadName]
                      /Feature/SizeDimension[Variable/@ID=$ID]/@Note"/>

如何保存最近10个产品?

3 个答案:

答案 0 :(得分:1)

您可以使用<div class="container"> <div class="main"> <h2>Login</h2> <form id="form_id" method="post" name="myform"> <label>User Name :</label> <input type="text" name="username" id="username" /> <label>Password :</label> <input type="password" name="password" id="password" /> <input type="button" value="Login" id="submit" onclick="validate()" /> </form> <span><b class="note">Note : </b>Have you forgotten your password? Request new password. <br/> </div> </div> 函数以json格式转换数组并将其保存在会话中。或者你甚至可以使用php json_encode(),但我个人更喜欢json因为对象序列化可能会导致一些漏洞

答案 1 :(得分:1)

试试这个:

$title = $node->title;
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; 
$img = $node->uc_product_image['und'][0]['filename'];
$product = array('title' => $title, 'url' => $url, 'img' => $img);

if (!isset($_SESSION['lastViewedProductsList'])) {
$_SESSION['lastViewedProductsList'][] = $product;
} else {
$_SESSION['lastViewedProductsList'][] = $product;
}

答案 2 :(得分:1)

$title = $node->title;
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; 
$img = $node->uc_product_image['und'][0]['filename'];
$product = array('title' => $title, 'url' => $url, 'img' => $img);

if (!isset($_SESSION['lastViewedProductsList'])) {
    // If the SESSION parameter does not exists, we create it as an array
    $products = array($product);
} else {
    // Else, we add the product in it
    $products = $_SESSION['lastViewedProductsList'];
    $products[] = $product;
    // We check if the array has more than 10 rows
    if(count($products) > 10){
        // If that's the case, we remove the first line in it to keep 10 rows in it
        array_shift($products);
    }
}

$_SESSION['lastViewedProductsList'] = $products;

如果您想检查产品是否已在阵列中,请检查此解决方案:PHP: Check if value and key exist in multidimensional array