我在php中有两个数组,我使用array_intersect函数来查找公共元素,如果存在公共元素,我想在第一个数组中显示这些公共元素的索引
这是我到目前为止所做的......
public static bool Logging(System.Reflection.MethodBase methodInfo)
{
var fullMethodName = methodInfo.DeclaringType.FullName + "." + methodInfo.Name;
if (error_flag == false)
{
using (StreamWriter outputFile = new StreamWriter(path + @"\log.txt", true))
{
outputFile.WriteLine(fullMethodName + ": OK");
}
}
else
{
using (StreamWriter outputFile = new StreamWriter(path + @"\log.txt", true))
{
outputFile.WriteLine("\n\n --> Error in : " + fullMethodName);
}
}
return true;
}
//Logging Method 2
public static bool WriteErrorLog(Exception ErrorMessage)
{
using (StreamWriter outputFile = new StreamWriter(path + @"\log.txt", true))
{
outputFile.WriteLine("{0} Exception caught.", ErrorMessage);
}
return true;
}
但是它不返回键有共同的元素是09:00:00和11:00:00当我通过11:00:00而不是$ array中的$ common时它会给出其他明智的结果$ common_array它不起作用,,请帮助我改进代码
答案 0 :(得分:0)
此函数返回一个数组,其中包含两个数组中的公共元素及其位置,如果找不到公共元素,则返回false
:
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;
}
测试:
$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);
输出:
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
答案 1 :(得分:0)
尝试使用array_keys函数
这是一个示例代码。希望它会对你有所帮助。
<?php
$a = array("a","b","c");
$b = array("c","d","a");
$c = array_keys(array_intersect($a,$b));
var_dump($c);
?>