如何从会话数组中删除重复值并更新它

时间:2016-04-26 08:29:15

标签: php arrays session

我有一个会话数组有很多重复值,我想删除重复并更新会话,这是我试过的

if (!isset($_SESSION['arry'])) {
    $_SESSION['arry'] = array();
}
$pu = $_POST['id']; // $pu is 12, 56, 97, 34, 63 post id can be anything here

$arrys = $_SESSION[ "arry" ] = array_merge( $_SESSION[ "arry" ],explode( ",",$pu) );
$_SESSION[ "arry" ] = array_unique($arrys);
$arrys =array_map('trim',$arrys);
print_r($_SESSION[ "arry" ]); exit;

当我打印数组时

Array ( [0] => 269 [1] => 270 [2] => 271 [3] => 272 [4] => 271 [5] => 273 ) Array ( [0] => 269 [1] => 270 [2] => 271 [3] => 272 [4] => 271 [5] => 273 ) Array ( [0] => 269 [1] => 270 [2] => 271 [3] => 272 [4] => 271 [5] => 273 ) Array ( [0] => 269 [1] => 270 [2] => 271 [3] => 272 [4] => 271 ) Array ( [0] => 269 [3] => 270 [4] => 271 [5] => 272 [6] => 271 ) Array ( [0] => 269 [3] => 270 [4] => 271 [5] => 272 [6] => 271 ) Array ( [0] => 269 [3] => 270 [4] => 271 [5] => 272 [6] => 271 ) Array ( [0] => 269 [3] => 270 [4] => 271 ) 

1 个答案:

答案 0 :(得分:0)

您可以使用以下两行删除数组中的重复条目:

$arrys = array_merge( $_SESSION[ "arry" ],explode( ",", $pu) );
$_SESSION[ "arry" ] = array_unique($arrys);

只要您向$_POST['id']提供相同格式的数据,您的代码是否循环无关紧要。值应始终相同。