[英]Can't delete first value of my array
我有一個腳本,可以根據其ID顯示產品。 在回顯的數據中,有一個鏈接可將用戶重定向到同一頁面,但帶有已發布的ID,根據該ID,我從會話中刪除一個數組的產品(ID)。 除第一個數組值外,這非常有效。 是什么原因造成的?
我現在如何獲得代碼:
//Link to quote page and send product id with it
echo '<p><a class="offertelink" href="offerte.php?product='.$productcr[0]['id'].'">Request a quote</a></p>';
在我的報價頁面上:
ob_start();
include 'includes/header.php';
if(!isset($_SESSION['product'])){
$_SESSION['product'] = array();
}
// Check if product is set before putting it in an array
if(isset($_GET['product']) && !in_array($_GET['product'], $_SESSION['product'])){
$_SESSION['product'][] = $_GET['product'];
}
// Implode array to use ids in query
$prods = implode(",", $_SESSION['product']);
查詢:
if(count($_SESSION['product']) != 0){
// Get all products with id in session
$offerte = "SELECT * FROM `web_content` WHERE `id` in (".$conn->real_escape_string($prods).") AND state = 1";
$offertecon = $conn->query($offerte);
$offertecr = array();
while ($offertecr[] = $offertecon->fetch_array());
}
最后在我的查詢下面:
// Check if id is send, and delete from session accordingly
if(isset($_GET['id'])){
$productID = $_GET['id'];
if( $index = array_search($productID, $_SESSION['product']) ) {
$_SESSION['product'][$index] = null;
unset($_SESSION['product'][$index]);
header('Location: http://www.web.nl/_extern/web/offerte.php');
}
}
if(count($_SESSION['product']) == 0){
echo 'No products added';
}else{
foreach($offertecr as $product){
$offerte_imgs = $product['images']; // Get image parameters of the article
$offertepic = json_decode($offerte_imgs); // Split the parameters apart
if($offertepic->{'image_intro'} != ''){
$image = 'cms/'.$offertepic->{'image_intro'};
}else{
$image = 'http://www.web.nl/_extern/web/cms/images/Producten/Untitled-7.jpg';
}
if($product['id'] != ''){
if (strlen($product['introtext']) > 100){
$shortcat = substr($product['introtext'], 0, 100) . '...';
}else{
$shortcat = $product['introtext'];
}
$deleteLink = "offerte.php?id=".$product['id'];
$offerteoverzicht .= '
<div class="row productofferte">
<a href="producten/'.$product['alias'].'.html">
<div class="col-md-6 offerteimg">
<img style="border:1px solid #ddd;" src="'.$image.'">
</div>
</a>
<div class="desc">
<a style="color:#2d4160;" href="producten/'.$product['alias'].'.html"><p style="font-weight:bold;">'.$product['title'].' </a>
<a href="'.$deleteLink.'">
<i class="fa fa-times" aria-hidden="true"></i>
</a>
</p>
<p>'.$shortcat.'</p>
</div>
</div>';
}
}
}
echo $offerteoverzicht;
我已經讀了一些關於我的問題的文章,並且認為如果我是正確的話,這與移動數組有關。 如果我打印我的會話,則除第一個數組外,所有數組均將從其中刪除。 不管它是什么ID,當我更改第一個產品時,都無法從會話中刪除該產品。
您使用array_search
在數組中查找元素的測試應與false
進行比較。 在做!
當找到的元素位於索引0時將返回false
:
更改:
if( $index = array_search($productID, $_SESSION['product']) ) {
至:
if( ($index = array_search($productID, $_SESSION['product'])) !== false ) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.