按值对xml中的数组进行分组

时间:2014-03-08 11:34:08

标签: php arrays sorting

Example Link

您好,我需要使用标记 curso 作为关键字在 identifyicador 标记之间对用户名进行排序,如上面的链接所示。我已经尝试过这个解决方案,但仍然无序。

$ dataClip给了我用户名(identificador)和$ dataClipCourse给我的课程(curso)。

编辑:processXML为我提供了所有用户名(identifyicadores)和processXMLCourse所有课程(curso)。

a.soveral

aj.sampaio

aa.reis

a.piedade

ac.tavares

a.meixeiro

acs.pires

ac.vieira

ac.ribeiro

acdo.rodrigues

389

167

450

167

450

450

167

450

167

169

$dataClip= processXML($content_b);
$dataClipCourse=processXMLforCourse($content_b);
$new_arr = array();

foreach($dataClipCourse as $dcc=>$dataClip)
{
    $new_arr[$dataClip['identificador']][$dcc]=$dataClip;
}
ksort($new_arr,SORT_NUMERIC);

以下是输出摘录:

数组([] =>数组([0] => SimpleXMLElement对象([0] => 167)1 => SimpleXMLElement对象([0] => 389)[2 ] => SimpleXMLElement对象([0] => 167)[3] => SimpleXMLElement对象([0] => 450)[4] => SimpleXMLElement对象([0] => 167)[ 5] => SimpleXMLElement对象([0] => 450)[6] => SimpleXMLElement对象([0] => 450)[7] => SimpleXMLElement对象([0] => 167) [8] => SimpleXMLElement对象([0] => 450)[9] => SimpleXMLElement对象([0] => 167)[10] => SimpleXMLElement对象([0] => 169 )[11] => SimpleXMLElement对象([0] => 167)[12] => SimpleXMLElement对象([0] => 167)[13] => SimpleXMLElement对象([0] => 167)[14] => SimpleXMLElement对象([0] => 167)[15] => SimpleXMLElement对象([0] => 389)[16] => SimpleXMLElement对象([0] => ; 167)[17] => SimpleXMLElement对象([0] => 167)[18] => SimpleXMLElemen t Object([0] => 450)[19] => SimpleXMLElement对象([0] => 172)[20] => SimpleXMLElement对象([0] => 167)[21] => SimpleXMLElement对象([0] => 167)[22] => SimpleXMLElement对象([0] => 450)

1 个答案:

答案 0 :(得分:0)

首先,我们假设输入数据采用以下格式:

$people = array( "Name A" => Array(450, 167), "Name B" => Array(629, 450) , ...);

因此,对于每个人,$people数组中都有一个条目,其中包含人名作为关键字,以及她作为值参加的课程数组。现在,将其转换为课程列表,其中人员列在课程编号旁边“反转”数组,因此课程编号成为关键,参与者列表成为值:

$courses = array( 450 => Array("Name A", "Name B"), 167 = Array("Name A"), 629 => Array("Name B") );

这可以通过这种算法来实现:

$courses = array();

// Iterate all persons
foreach( $people as $name => $attendedCourses)
{
    // Iterate all attended courses of this person
    foreach( $attendedCourses as $courseNumber )
    {
        // Check if the current course was already remembered
        if( isset($courses[$courseNumber] ) )
        {
            // Add person to the list of attendees
            $courses[$courseNumber][] = $name;
        }
        else 
        {
            // Create list of attendees with the
            // current person as the single attendee
            $courses[$courseNumber] = array( $name );
        }
    }
}

// Sort by keys
ksort( $courses );

// Output
print_r( $courses );

但是你必须将SimpleXML节点列表转换为更简单的输入格式。