如何检查数组是否包含另一个数组的值?

时间:2018-04-01 20:00:03

标签: php

我有2个数组,每个数组var_dump()都在下面。

我尝试使用array_intersect(),但没有返回任何内容,也没有错误:

if (array_intersect($userInterests, $interests)) {
   echo "found";
}

小数组,$ userInterests:

array(3) {
  [0]=>
  object(stdClass)#8 (1) {
    ["interestId"]=>
    string(1) "2"
  }
  [1]=>
  object(stdClass)#6 (1) {
    ["interestId"]=>
    string(1) "3"
  }
  [2]=>
  object(stdClass)#9 (1) {
    ["interestId"]=>
    string(1) "5"
  }
}

大阵容,$ interest:

array(15) {
  [0]=>
  object(stdClass)#2 (2) {
    ["interestName"]=>
    string(5) "Musik"
    ["interestID"]=>
    string(1) "1"
  }
  [1]=>
  object(stdClass)#11 (2) {
    ["interestName"]=>
    string(3) "Mad"
    ["interestID"]=>
    string(1) "2"
  }
  [2]=>
  object(stdClass)#12 (2) {
    ["interestName"]=>
    string(6) "Rejser"
    ["interestID"]=>
    string(1) "3"
  }
  [3]=>
  object(stdClass)#13 (2) {
    ["interestName"]=>
    string(10) "Mad Moneyz"
    ["interestID"]=>
    string(1) "4"
  }
  [4]=>
  object(stdClass)#14 (2) {
    ["interestName"]=>
    string(5) "Biler"
    ["interestID"]=>
    string(1) "5"
  }
  [5]=>
  object(stdClass)#15 (2) {
    ["interestName"]=>
    string(7) "Netflix"
    ["interestID"]=>
    string(1) "6"
  }
  [6]=>
  object(stdClass)#16 (2) {
    ["interestName"]=>
    string(26) "Lange gåture på stranden"
    ["interestID"]=>
    string(1) "7"
  }
  [7]=>
  object(stdClass)#17 (2) {
    ["interestName"]=>
    string(15) "Bjergbestigning"
    ["interestID"]=>
    string(1) "8"
  }
}

我的目标是将所选选项标记为已选择,如下所示:

<option value="<?php echo $interest->interestID; ?>"<?php echo (in_array($interest->interestID, $userInterests)) ? ' selected="selected"' : ''; ?>><?php echo $interest->interestName; ?></option>

$ interest是从更大的阵列中获得的特定利益,$ interest

$ userInterests是较小的数组

2 个答案:

答案 0 :(得分:0)

将它们与array_merge()合并,并比较元素数量sizeof()

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

if(sizeof(array_merge($array1, $array2)) < sizeof($array1) + sizeof($array2))
    //Common values

要检查元素是否在数组中,请使用in_array()

答案 1 :(得分:0)

问题是你的第一个数组实际上是一个对象数组。你基本上问你的PHP这个对象数组是否包含3?这显然不是一个有效的问题。您需要将对象数组转换为一组数字。

array(3) {
  [0]=>
    object(stdClass)#8 (1) {
      ["interestId"]=>
        string(1) "2"
    }
  [1]=>
    object(stdClass)#6 (1) {
      ["interestId"]=>
        string(1) "3"
    }
  [2]=>
    object(stdClass)#9 (1) {
      ["interestId"]=>
        string(1) "5"
    }
}

array(3) {
  [0]=>
    string(1) "2"
  [1]=>
    string(1) "3"
  [2]=>
    string(1) "5"
}

首先,将用户的兴趣转换为简单数组。

$userInterestsSimple = array();
foreach ($userInterests as $userInterest)
    $userInterestsSimple[] = $userInterest->interestId;

之后,使用in_array()进行的检查将正常运行:

<option value="<?php echo $interest->interestID; ?>"
  <?php
    echo (in_array($interest->interestID, $userInterestsSimple)) ? ' selected="selected"' : '';
  ?>
>
    <?php echo $interest->interestName; ?>
</option>
相关问题