【问题标题】:How to use the array intersect method to match two values within 2 sets of arrays如何使用数组相交方法匹配2组数组中的两个值
【发布时间】:2015-08-14 04:52:41
【问题描述】:

我有这个问题:

$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 至少有 1 个匹配值作为它执行我显示的查询的条件在底部。我假设它是 arrayintersect 方法,但我不确定如何使用它。

$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(); 

}

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

【问题讨论】:

    标签: php sql laravel eloquent


    【解决方案1】:

    如果$values$subcommon 都是有效数组,您可以使用array_intersect 函数来比较它们:

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

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

    来自php documentation的一个很好的例子:

    $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)
    }
    

    【讨论】:

    • 谢谢,但是array_intersect 方法给了我一个错误,说数组到字符串的转换。我现在编辑了我的问题,在底部给出了部分解决方案
    • 要匹配这些值,只需使用array_intersect 函数。它会给您此错误,因为您可能在实际需要转储数组时尝试回显或打印数组。什么代码实际上导致了数组到字符串的转换错误?
    • 对不起,我的意思是键和值是我的错误。所以对于上面的例子,我想匹配来自第一个查询的subjectlist_id:1 和来自我的第二个查询的subjectlist_id:1。最终我想回显$newquery 而不是数组,但我得到了错误
    • 哦,那您可以使用array_intersect_assoc() 来匹配两个数组中的键值。 :) 请注意,您不能回显$newquery,因为它也是一个数组(来自数据库),因此您必须使用var_dumpprint_r 才能看到结果。
    • 我得到同样的错误Array to string conversion@Shay 但是当我这样做时array_intersect_key 我没有得到一个错误,但它只是匹配键
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多