dsvyc66464 2016-08-25 08:38
浏览 159

比较两个数组并返回php中公共元素的索引

i have two arrays in php and i am using the array_intersect function to find the common elements and if common elements exists i want to display the index of theses common elements in the 1st array

here is what i have done so far..

  function check_if_exists($company_timings,$in_time)


   {    

     $length_of_company=sizeof($company_timings);
      $length_of_emp=sizeof($in_time);
       $common=array_intersect($company_timings,$in_time);
        $length_of_common=sizeof($common);
       $key=array_search($common,$company_timings);
      return $key;


    }

but its not return the keys there are common elements which are 09:00:00 and 11:00:00 and when i pass 11:00:00 rather than $common in array_search then it gives the accurate result other wise with the $common_array it doesn't work,,,kindly help me in ameliorating the code

  • 写回答

2条回答 默认 最新

  • dongzaobei0942 2016-08-25 08:52
    关注

    This function returns an array containing the common elements and their positions in both array, or falseif no common elements are found :

    function check_if_exists($arr1, $arr2) {
        $combined = array_intersect($arr1, $arr2);
        if (empty($combined))
            return false;
        $return = array();
        foreach ($combined as $elmt) {
            $return[$elmt] = array();
            $return[$elmt]['arr1'] = array_search($elmt, $arr1);
            $return[$elmt]['arr2'] = array_search($elmt, $arr2);
        }
        return $return;
    }
    

    Test :

    $array1 = array('a', 'b', 'c', 'd');
    $array2 = array('b', 'f', 'g', 'c');
    $array3 = array('n', 'o', 'p', 'e');
    
    $exists = check_if_exists($array1, $array2);
    var_dump($exists);
    $exists_no = check_if_exists($array1, $array3);
    var_dump($exists_no);
    

    Output :

    array (size=2)
      'b' => 
        array (size=2)
          'arr1' => int 1
          'arr2' => int 0
      'c' => 
        array (size=2)
          'arr1' => int 2
          'arr2' => int 3
    
    boolean false
    
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀