如何使用数组相交方法来匹配2组数组中的两个值 [英] How to use the array intersect method to match two values within 2 sets of arrays

查看:124
本文介绍了如何使用数组相交方法来匹配2组数组中的两个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个查询:

$subcommon= MyModel::selectRaw('subjectlist_id, count(subjectlist_id) AS aggregate')
 ->whereIn('user_id', [Auth::id(), $user->id])
->groupBy('subjectlist_id')  
->having('aggregate','>',1)
->get();

给出了这个查询结果:

{"subjectlist_id":1,"aggregate":2} {"subjectlist_id":3,"aggregate":2}

我也有这个查询:

$values = Mysecondmodel::where('user_id', Auth::id())
                         ->first(); 

其中给出了以下结果:

{"id":1,"subjectlist_id":1, "article_id":4}

因为我觉得加入这两个模型太难了,我决定输出它们作为数组,所以我想至少有一个匹配的值为 subjectlist_id 作为它执行查询的一个条件,我已经在底部显示。我假设它是 arrayintersect 方法,但是我不知道如何使用它。

Because im finding it way too difficult to join these two models i've decided to output them as arrays so I would like at least 1 matching value for subjectlist_id as a condition for it to execute the query I've displayed at the bottom. I'm assuming it's the arrayintersect method however im unsure how to use it.

$values = Mysecondmodel::where('user_id', Auth::id())
                           ->first(); 

我有这个目的:

 $subcommonarray = (array) $subcommon;

$valuesarray = (array) $values;

$a = $subcommonarray;
$b = $valuesarray;
$c = array_intersect_key($a, $b);

if (count($c) > 0) {


   $newquery = Mysecondmodel::where(user_id, Auth::id())
 ->first(); 

}

但是我认为是比较键而不是值。如何匹配值和密钥在一起?

But this I think is comparing the keys and not the values. How do I match the values and and the key together?

推荐答案

如果 $ values $ subcommon 都是有效的数组,您可以使用 array_intersect 函数进行比较: / p>

Well if $values and $subcommon are both valid arrays, you could compare them using the array_intersect function like that:

$subjectlist_id = array_intersect($values, $subcommon);

这将在中搜索相似之处,并将构建另一个数组在两个数组之间的所有匹配值的 $ subjectlist_id 变量中。

This would go and search for similarities in values, and will construct another array in the $subjectlist_id variable of all the matching values between both arrays.

php文档

$array1 = array(2, 4, 6, 8, 10, 12);
$array2 = array(1, 2, 3, 4, 5, 6);

$array3 = array_intersect($array1, $array2);
var_dump($array3);

这将有一个数组:

array(3) {
  [0]=> int(2)
  [1]=> int(4)
  [2]=> int(6)
}

这篇关于如何使用数组相交方法来匹配2组数组中的两个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆