我想要做的是在数组中获取相同的值,在数组中删除相同的值,然后在数组中删除相同的值后得到整数
这是我的代码,但卡住了
$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;
知道如何解决我的问题吗? 感谢
答案 0 :(得分: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
答案 1 :(得分: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));
答案 2 :(得分: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);
答案 3 :(得分: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;
答案 4 :(得分: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;
}
}
?>
使用的功能:
答案 5 :(得分:0)
你可以试试这个。
$userid = array("1087","1088","1089","1090","1091");
foreach($userid as $key=>$id){
if($id == 1088){
unset($userid[$key]);
}
}
print_r($userid);