开发者

Output an array

I have created a shortlist feature which acts a bit like a shopping cart. I output the items in the shortlist by:

$i = 0;
while ($i < $countArray){

echo $_SESSION['shortlistArray'][$i]." <a href='shortlistRemoveItem.php?arrayID=$i'>[x]</a><br />";

$i++;
}

and delete an item by

$arrayID = $_GET["arrayID"];
unset($_SESSION['shortlistArray'][$arrayID]);

The problem is that when I delete an item from an array such as $_SESSION['shortlistArray'][2] the output is all messed up as the array is no londer sequential. Should 开发者_如何学CI recode the way my array is outputted or the way I am deleting an item from an array?


The most efficient solution would be simply changing the way your array is outputted:

foreach($countArray as $key => $item){

    echo $_SESSION['shortlistArray'][$key]." <a href='shortlistRemoveItem.php?arrayID=$key'>[x]</a><br />";
}

If you insist on changing the way you are deleting an item from the array, consider this alternative:

$arrayID   = $_GET["arrayID"];
$tempArray = array();

foreach($countArray as $key => $item){

    if($arrayID == $key) continue;
    $tempArray[] = $item;
}

$_SESSION['shortlistArray'] = $tempArray;

I' recommend the first option though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜