查找一个数组中的元素是否存在于php中的另一个数组中

时间:2018-01-25 19:23:18

标签: php arrays string

我有两个数组 array_one array_two ,我想从这两个数组中找到类似的元素

   $get1= "SELECT list FROM `data` WHERE sess_id=1 ";
   $result1 = $conn->query($get1);

   $array_one = array();

   while($row = $result1->fetch_assoc()) { 
    echo $row["list"]. "<br>";
    $array_one[] = $row;

    // OR just echo the data:
    echo $row['list']."<br>"; // etc
     }
    print_r($array_one);

    $get2= "SELECT * FROM `questions`";
    $result2 = $conn->query($get2); 

    $array_two = array();

    while($row = $result2->fetch_assoc()) { 
      $array_two[] = $row;

    } 
    echo    "array_two is this".$array_two[3]['type']."<br>"; 
    $result_one = array_intersect($array_one, $array_two);
    var_dump($result_one);
    print_r($result_one);

这是array_one中的数据:

    Array ( [0] => Array ( [list] => 2 ) [1] => Array ( [list] => hello ) 
    [2] => Array ( [list] => 2 ) [3] => Array ( [list] => 2 ) [4] => Array ( 
    [list] => easy ) [5] => Array ( [list] => easy ) [6] => Array ( [list] 
    => medium ) [7] => Array ( [list] => easy ) [8] => Array ( [list] => 
    will ) [9] => Array ( [list] => easy ) [10] => Array ( [list] => will ) 
     )

这是array_two中的数据:

     Array ( [0] => Array ( [type] => HTML ) [1] => Array ( [type] => head ) 
     [2] => Array ( [type] => web ) [3] => Array ( [type] => background ) 
     [4] => Array ( [type] => list ) [5] => Array ( [type] => link ) [6] => 
     Array ( [type] => comment ) [7] => Array ( [type] => paragraph ) [8] => 
     Array ( [type] => list ) [9] => Array ( [type] => paragraph ) [10] => 
     Array ( [type] => list ) [11] => Array ( [type] => text ) [12] => Array 
     ( [type] => html ) [13] => Array ( [type] => html ) [14] => Array ( 
     [type] => html ))

现在我想看看这两个中是否有任何共同的元素,array_intersect方法的结果也是

  

注意:数组到字符串转换错误

1 个答案:

答案 0 :(得分:0)

通过array_column获取值并使用array_intersect

array_intersect(array_column($arr1, 'list'), array_column($arr2, 'type')