i want compare values of 2 arrays have same key (the activity) , have same length.
arrays
$anna_array = array("soccer" => "10", "basketball" => "20", "atletics" => "40"); $john_array = array("soccer" => "15", "basketball" => "15", "atletics" => "45");
i want have like:
<?php if ($anna_array['soccer'] > $john_array['soccer']){ $points = "1"; } else { $points = "0"; } ?>
then use $points in results:
<?php foreach ($anna_array $x => $x_value) { $speler1_prestaties = "<span class=\"white bold\">".str_pad($count1++, 2, "0", str_pad_left)."</span> ".$x.": <span class=\"orange\">".$x_value." "(".$points .")></span><br />"; echo $player1_info; ?>
any appreciated.
first, can retrieve common keys first applying array_intersect_key
, array_keys
.
$common_sports = array_keys(array_intersect_key($anna_array, $john_array));
then can use array_fill_keys
fill array same keys find above
$points_anna_array = $points_john_array = array_fill_keys($common_sports, 0);
the array here generated is:
array(3) { ["soccer"]=> int(0) ["basketball"]=> int(0) ["atletics"]=> int(0) }
now can compare activity of anna , john
foreach ($common_sports $common_sport) { if ($anna_array[$common_sport] > $john_array[$common_sport]) { $points_anna_array[$common_sport]++; } else if ($anna_array[$common_sport] < $john_array[$common_sport]) { $points_john_array[$common_sport]++; } }
at point $points_anna_array
's value this:
array(3) { ["soccer"]=> int(0) ["basketball"]=> int(1) ["atletics"]=> int(0) }
and $points_john_array
value:
array(3) { ["soccer"]=> int(1) ["basketball"]=> int(0) ["atletics"]=> int(1) }
so:
foreach ($common_sports $common_sport) { echo sprintf( 'anna(%s) %d vs john(%s) %d'."\n", $common_sport, $points_anna_array[$common_sport], $common_sport, $points_john_array[$common_sport] ); }
this output:
anna(soccer) 0 vs john(soccer) 1 anna(basketball) 1 vs john(basketball) 0 anna(atletics) 0 vs john(atletics) 1
demo.
to total score, can use array_sum
.
echo "john's total score: ", array_sum($points_john_array); echo "anna's total score: ", array_sum($points_anna_array);
Comments
Post a Comment