对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>>();
我当前的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.
}
如何将分数添加到$ yearScores数组中的正确年份数组?
答案 0 :(得分: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);
}
}
}
我不确定if
但是(查看我的评论)。你检查过它们的输出是否正确吗?