Number of points per year in the array

Pretty new to PHP and I'm trying to achieve something that I think can be done easily in C #. However, in PHP this is not easy to achieve for me.

When iterating over the XML file, I want to store all the average scores per year. The years will be unique, the scores must be their values.

The output should look like this:

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

This way I can get all the average scores from 2014, etc. In C #, I would create a dictionary containing a list like:

var yearScores = new Dictionary<string, List<Decimal>>();

      

My current PHP code looks like this:

$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.
}

      

How do I add the scores to the correct year arrays in the $ yearScores array?

+3


source to share


1 answer


You can do it like this:

// 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);
        }
    }
}

      



However, I am not sure about if

(mark my comment). Have you checked if their conclusion is correct?

+5


source







All Articles