比较两个数组并检索第二个数组的值

时间:2015-11-19 14:31:01

标签: php mysql

array1 = array();

array2 = array();

两个数组都有来自数据库的值;

Array2包含训练列表,而array1包含已经进行的训练列表。

我想将array1与array2进行比较,并检索不在array1中的训练列表

以下是我目前正在执行的代码片段:

$query2 = "SELECT trainingName, rank FROM crewtraininglist WHERE crewId = '$crewId'";
$result2 = mysqli_query($conn, $query2);

$array = array();
while($row = mysqli_fetch_assoc($result2)) 
{        
    $rank = $row['rank'];
    $training = $row['trainingName'];
    $array[] = $row['trainingName'];
    echo "<li>$training</li>";
    //echo "<option value='{$row['name']}'>{$row['name']}</option>";
}

$array2 = array();

$query3 = "SELECT `trainingName`, `rank` FROM `traininglist` WHERE rank LIKE '%$rank%'";
$result3 = mysqli_query($conn, $query3);
while($row = mysqli_fetch_assoc($result3)) 
{
    $array2[]=$row['trainingName'];        
}

$array3 = array_diff($array,$array2);
print_r ($array3);

数组1的输出是:

Array ( 
    [0] => License + COC & Endrs. 
    [1] => Basic Training + COP 
)

Array2的输出是:

Array ( 
    [0] => License + COC & Endrs. 
    [1] => Basic Training + COP 
    [2] => Personal Safety & Social Responsibility 
    [3] => Proficiency in Survival Craft & Rescue Boat (PSCRB) + COP 
    [4] => Advance Training in Firefighting (AFF) + COP 
    [5] => Medical Emergency First Aid (MEFA) + COP 
    [6] => Medical Care (MECA) + COP [7] => Radar Observing & Ploting Courses (ROC) 
    [8] => Operational Use of Automatic Radar Ploting Aids (ARPA) 
    [9] => Radar Simulator Course (RSC) 
    [10] => Ship Simulator & Bridge Team Work (SSBT) w/BRM 
)

1 个答案:

答案 0 :(得分:4)

使用array_diff()

$array1 = array()// from database
$array2 = array()// from database

$array3 = array_diff($array2,$array1);

有关详细信息,请参阅this