I am trying to figure out how to divide the values in one associative array with the values in another, and put the results into a third associative array. The two starting arrays have the same key values: e.g…
So how to divide the ‘HO’ value in the first array by the ‘HO’ value in the second, and so on ?
I can’t help feeling it should be very easy, but I want to avoid citing the keys themselves (they may change, but will always be the same in both arrays). It would be easier if the keys were numerical, as I could use a ‘for’ loop, but I need the keys in the result.
Perhaps I can bend array_walk to the task, but I’m struggling. Any ideas, please ?
I thought this was an interesting exercise, so here’s what I came up with:
<?php
$bus_type_totals = array('HO' => 15357, 'GH' => 3564, 'BB' => 62475, 'SC' => 247575, 'CP' => 3145, 'HS' => 7322, 'CS' => 2466);
$bus_type_sample = array('HO' => 234, 'GH' => 135, 'BB' => 236, 'SC' => 754, 'CP' => 54, 'HS' => 865, 'CS' => 432);
/* check for data integrity before performing calculations */
if(keys_are_equal($bus_type_totals,$bus_type_sample)){
$the_calculated_value = -1;
$keys = array_keys($bus_type_totals); /* returns an array of the keys listed in the array */
foreach($keys as $key ){
$the_calculated_value=$bus_type_totals[$key]/$bus_type_sample[$key]; /* I'm not sure which way you're actually dividing the values, so feel free to change as necessary */
/* do something with the calculated value here */
echo $key.': '.$the_calculated_value;
echo '<br>';
/* maybe save the resulting value in an array for later use, or use it for something else here */
}
}
else {
echo 'error: array mismatch';
}
/* this function verifies that the two arrays have the same keys */
function keys_are_equal($array1, $array2) {
return !array_diff_key($array1, $array2) && !array_diff_key($array2, $array1);
}
?>
<?php
$bus_type_totals = array('HO' => 15357, 'GH' => 3564, 'BB' => 62475, 'SC' => 247575, 'CP' => 3145, 'HS' => 7322, 'CS' => 2466);
$bus_type_sample = array('HO' => 234, 'GH' => 135, 'BB' => 236, 'SC' => 754, 'CP' => 54, 'HS' => 865, 'CS' => 432);
$the_calculated_value = -1;
$keys = array_keys($bus_type_totals); /* returns an array of the keys listed in the array */
foreach($keys as $key ){
$the_calculated_value = -1; //set a default value for each loop so you can identify when you don't actually get a result
if($bus_type_sample[$key]>0){ /* if the divisor is greater than zero, go ahead with the calculation */
$the_calculated_value=$bus_type_totals[$key]/$bus_type_sample[$key];
/* your code to handle the result */
}
else{
echo $key.' is zero. Calculation cannot be processed.';
}
}
?>