ai didi

php - 比较 2 个数组并删除相似的值

转载 作者:行者123 更新时间:2023-11-29 03:29:55 24 4
gpt4 key购买 nike

我有两个数组

第一个是这样的

$sql1 = "SELECT userid FROM interest where interest='".$interest."' and userid!='".$myuserid."'";
$result1 = mysqli_query($conn, $sql1);
if (mysqli_num_rows($result1) > 0)
{
while($row1 = mysqli_fetch_assoc($result1))
{
$userid = $row1["userid"];
$user[] = array($userid);
}
echo "<pre>";
print_r ($user);
echo "</pre>";
}

它的o/p是这样的

 Array
(
[0] => Array
(
[0] => 8
)

[1] => Array
(
[0] => 9
)

[2] => Array
(
[0] => 2
)
[3] => Array
(
[0] => 1
)

)

第二个是这样的

 $sql = "SELECT * FROM block where blockedby='".$myuserid."'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$blockeduser=$row["blockeduser"];
$block[] = array($blockeduser,$myuserid);
}

echo "<pre>";
print_r ($block);
echo "</pre>";

}

它的o/p是这样的

Array
(
[0] => Array
(
[0] => 1
[1] => 2
)

)

我想比较这两个数组并删除结果数组中的相似值..我应该作为最终结果得到的数组应该是这样的

Array
(
[0] => Array
(
[0] => 8
)

[1] => Array
(
[0] => 9
)

)

我试过了

 $unique=array_unique( array_merge($block, $user) );
$block=array_diff($unique, $block);
print_r($block);

但我得到了这个结果

 Array
(
)

谁能告诉我怎样才能达到这个结果

最佳答案

Array_unique 不能用于多维数组。让我们通过array_filter 实现它的功能

$values = array();

$new = array_filter(array_merge($block, $user),
function($i) use(&$values) {
if( !in_array($i[0], $values))
{ $values[] = $i[0]; return true;}
return false; });

关于php - 比较 2 个数组并删除相似的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31715232/

24 4 0
文章推荐: java - 调用方法将行添加到java中的文本文件
文章推荐: java - 如何用表和一些数据在内存中预填充 Derby?
文章推荐: 正在计算事物时的 iOS 事件指示器
文章推荐: java - 如何针对测试数据库运行 Rest assured?
行者123
个人简介

我是一名优秀的程序员,十分优秀!

滴滴打车优惠券免费领取
滴滴打车优惠券
全站热门文章
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com