关于array_intersect

时间:2014-02-05 12:14:36

标签: php moodle array-intersect

我有2个数组。一个来自Moodle($ allUsers)的用户名,另一个来自外部源($ dataClip)的用户名。我需要比较它们并批量添加它们,如果尚未注册的话。

function buildURL($year, $period, $typeperiod,$course)
{
return 'https://clip.unl.pt/sprs?lg=pt&year='.$year.'&uo=97747&srv=rsu&p='.$period.'&tp='.$typeperiod.'&md=3&rs='.$course.'&it=1030123459';
}

function doRequest_with_FileGetContents($url)
{
return file_get_contents($url);
}

function getallUsers(){
global $DB;
$allusers=array();
$users= $DB->get_records('user');
foreach($users as $user){
$allusers[]= $user->username."<br/>";

}
return $allusers;
}
function processXML($xmlContent){
$xmlObj= new SimpleXMLElement($xmlContent);
$result=array();
foreach($xmlObj->unidade_curricular->inscritos->aluno as $aluno){
$result[]= $aluno->identificador."<br/>";

}
return $result;
}

$allUsers= getallUsers();
$dataClip= processXML($content_b);
$courseid= required_param('id', PARAM_INT); 
$context= get_context_instance(CONTEXT_COURSE, $courseid);//Getting students who are already enrolled                                                     
$students= get_role_users(5,$context);

if(is_array($dataClip)){ //eliminates warnings of Invalid Argument supplied in foreach
foreach($dataClip as $newdata){
    $duplicate=false;
    if(is_array($allUsers)){
    foreach($allUsers as $dataMoodle){
        // if there is a match
        if($newdata==$dataMoodle){
            // if student is enrolled on moodle course page.
           if($students){
           $duplicate=true;
        continue;
            }
    else {
        $duplicate=false;
        $results=array_intersect((array)$newdata,(array)$dataMoodle); // complains about not being an array
        //print_r($results);
        echo implode('<br/>',$results);
}

else{
    $duplicate= false;
    continue;
    } 
}
}
}
}

array_intersect为我提供了两个数组之间的公共用户名,但是当我将其中一个添加到我的课程页面时,我没有输出。所以,就像abc和ab之间的交集是[]而不是ab。

编辑:dataCLIP有300多个名字,但其中有

a.maia

a.cabral

d.mateus

这是Moodle的所有用户

管理员

xpto.xy

a.maia

d.mano

a.cabral

d.mateus

我的逻辑在哪里失败?

1 个答案:

答案 0 :(得分:1)

对于注册用户,您可能需要查看/lib/enrollib.php中的函数enrol_user_bulk(stdClass $ instance,$ userids,...)

像这样的东西

$plugin = enrol_get_plugin('manual');
$courses = ... // get the distinct course ids
foreach ($courses as $course) {
    $instance = $DB->get_record('enrol', array('courseid' => $courseid, 'enrol' => 'manual');
    $userids = ... // get userid's to enrol on this course
    $plugin->enrol_user_bulk($instance, $userids) 
}