Reputation: 65
I'm sure this is simple and I'm just failing at phrasing it correctly for google. Hopefully I can spell it out well enough here that someone can point me in the right direction!
I'm using php and chart.js to chart stats about mma fighters and I want to chart how many wins (or losses or ko's, etc. etc. they had per year.
I've been able to create an array that shows the year of each loss (note that there are repeats in there went multiple losses occurred in a year)
e.g.
$loss_years = Array ( [0] => 2019 [1] => 2016 [2] => 2014 [3] => 2013 [4] => 2012 [5] => 2011 [6] => `2011 [7] => 2010 [8] => 2009 [9] => 2009 [10] => 2006 [11] => 2005 )`
I've been able to count how many losses occur in each of the years that losses do occur like so:
array_count_values(array_reverse ($loss_years)));
Which outputs:
array(10) { ["2005 "]=> int(1) ["2006 "]=> int(1) ["2009 "]=> int(2) ["2010 "]=> int(1) ["2011 "]=> int(2) ["2012 "]=> int(1) ["2013 "]=> int(1) ["2014 "]=> int(1) ["2016 "]=> int(1) ["2019 "]=> int(1) }
However I want to be able to cross-reference it with every year of their career.
So if their career span is represented as:
$career_span = Array ( [0] => 2004 [1] => 2005 [2] => 2006 [3] => 2007 [4] => 2008 [5] => 2009 [6] => 2010 [7] => 2011 [8] => 2012 [9] => 2013 [10] => 2014 [11] => 2015 [12] => 2016 [13] => 2017 [14] => 2018 [15] => 2019 [16] => 2020 )
Then I want to cross-reference that with $loss_years and output a third array $losses_per_year that'd look something like :
Array ( [0] => 0 [1] => 1 [2] => 1 [3] => 0 [4] => 0 [5] => 2 [6] => 1 [7] => 2 [8] => 1 [9] => 1 [10] => 1 [11] => 0 [12] => 1 [13] => 0 [14] => 0 [15] => 1 [16] => 0 )
Does that make sense?
Is there some much simpler way to go about it that I'm not finding?
Upvotes: 0
Views: 45
Reputation: 3126
Loop through the $career_span
array with a foreach
loop and check the number of losses for each career year in the $loss_years
array (after applying array_count_values
to it).
You can use the PHP ternary operator to check if the there is an array key in $loss_years
that matches the career year. If so, add the number of losses for that year. If not, add zero.
$loss_years = array_count_values( $loss_years );
foreach ( $career_span as $career_year ) {
$losses_per_year[] = array_key_exists( $career_year, $loss_years ) ? $loss_years[$career_year] : 0;
}
Upvotes: 1