每年得分数

Max*_*Max 3 php arrays

PHP的新手,我正在努力实现某些目标,在我看来,这可以在c#中轻松完成.但是在PHP中,对我来说并不容易实现.

迭代XML文件时,我想存储每年的所有平均分数.这些年份将是独一无二的,分数应该是他们的价值观.

输出应该像:

['2012'] =>数组(8.1,7.3,8.8)
['2013'] =>数组(6.7,7.7,5.5)
['2014'] =>数组(2.3,7.9,9.9)

通过这种方式,我可以获得2014年的所有平均分数等.在c#中我会创建一个包含List的字典,如:

var yearScores = new Dictionary<string, List<Decimal>>();
Run Code Online (Sandbox Code Playgroud)

我目前的PHP代码如下:

$yearScores = array(array());
foreach($xml->results->children() as $result) {
        //Reset variables
        $current_date = null;
        $current_average = null;

        //Iterate over all 'answer' children in result
        foreach($result->children() as $answer) {
            //Retrieve Date and Average
            if($average[0]['name'] == "date") {
                $current_date = date('Y', strtotime($answer));
            }
            if($average[0]['name'] == "average") {
                $current_average = $answer;
            }
        }

        //Validate if we found both current Date and current Average
        if(is_null($current_date) || is_null($current_average)) continue;

        //The Date and Average exist
        //See if the Datum already exists in our array
        if(!in_array($current_date, $yearScores)) {
            $yearScores[] = $current_date;
        }
        //The average should be added to the correct year in the array here.
}
Run Code Online (Sandbox Code Playgroud)

如何将分数添加到$ yearScores数组中的正确年份数组?

Vol*_*enD 5

你可以这样做:

// no need to initialize multidimensional array here
$yearScores = array();

foreach($xml->results->children() as $result) {

    foreach($result->children() as $answer) {
        //Retrieve Date and Average
        // This here does not look right to me
        if($average[0]['name'] == "date") {
            $current_date = date('Y', strtotime($answer));
        }
        if($average[0]['name'] == "average") {
            $current_average = $answer;
        }

        if(!isset($yearScores[$current_date])) {
            $yearScores[$current_date] = array($current_average);
        } else {
            array_push($yearScores[$current_date], $current_average);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我不确定ifs(请查看我的评论).你检查过他们的输出是否正确吗?