-1

我想要做的是在数组中获取相同的值,在数组中删除相同的值,然后在删除数组中的相同值后获取整体

这是我的代码,但卡住了

$userid = "1087,1088,1089,1090,1091";
$user_explode = explode(",",$userid);
$got_user = "no";
foreach($user_explode as $userid_row){
    if($userid_row == 1088){
      $got_user = "yes";
    }
}

这就是我要的

$id = '1,2,3,4,5';
if($id == 2){
 $result = '1,3,4,5';
}
echo $result;

知道如何解决我的问题吗?谢谢

4

6 回答 6

1

为什么不array_filter呢?

<?php

$id = '1,2,3,4,5';
$result = implode(',', 
    array_filter(
        explode(',', $id),
        function($id) {
            if ($id != 2)
                return true;
        }
    )
);

echo $result;

结果:

1,3,4,5
于 2013-08-12T04:54:31.147 回答
0

您使用unset()删除不需要的值。

$userid = "1087,1088,1089,1090,1091";
$user_explode = explode(",",$userid);
$got_user = "no";
foreach($user_explode as $key => $userid_row){
    if($userid_row == 1088){
      unset($user_explode[$key]);
      $got_user = "yes";
    }
}

echo(implode(',',$user_explode));
于 2013-08-12T04:47:43.757 回答
0

您可以爆炸到阵列,删除项目并返回阵列。

$userid = "1087,1088,1089,1090,1091";
$user_explode = explode(",",$userid);
$ids = array_flip($user_explode);
unset($ids['1088']);
$user_explode = array_flip($ids);
$final = implode(",", $user_explode);
于 2013-08-12T04:50:05.883 回答
0

您可以使用array_search函数来获取您正在搜索的值的键。如果找到键,则从数组中取消设置元素,最后使数组内爆并将其回显。

尝试:

$userid = "1087,1088,1089,1090,1091";
$user_explode = explode(",",$userid);
$got_user = "no";

$found_key = array_search('1088', $user_explode);
if ($found_key !== false) {
  unset($user_explode[$found_key]);
}

$result = implode(',', $user_explode);
echo $result;
于 2013-08-12T04:50:21.000 回答
0
<?php
    $id = "1,2,3,4,5";
    $got_id = false; // Not found by default
    $ids_array = array_map("intval", explode(",", $id)); // intval just to make sure these are correct IDs, I mean, transform them to integers
    $search = 2; // You're searching for id = 2

    foreach ($ids_array AS $key => $value)
    {
        if ($value == $search) // ID exists, remove it from the array and return the modified array
        {
            unset($ids_array[$key]);
            $result = implode(",", $ids_array);
            $got_id = true; // Found ID
            echo $result;
        }
    }
?>

使用的功能:

数组映射

爆炸

内爆

间隔

未设置

于 2013-08-12T04:50:22.147 回答
0

你可以试试这个。

$userid = array("1087","1088","1089","1090","1091");
foreach($userid as $key=>$id){
    if($id == 1088){
        unset($userid[$key]);
    }
}
print_r($userid);
于 2013-08-12T04:56:08.050 回答