php - Find min/max of complex 2D array -
php not language please bear me.
i have (in opinion) poorly designed 2d array of product categories , min/max of 2 ratings per sub-category. sadly, cannot change layout of array:
[[category, subcategory, overallrating, extrarating]]
for example, sample data this:
[["fridges", "samsung", 5, 6], ["fridges", "samsung", 2, 1], ["fridges", "samsung", 3, 4], ["fridges", "lg", 7, 5], ["washing machine", "letto", 5, 6], ["washing machine", "samsung", 5, 6], ["fridges", "samsung", 4, 4]]
the output of should give me data such that:
fridges, samsung: 2/5, 1/6 fridges, lg: 7/7, 5/5 (or 7, 5) washing machine, letto: 5, 6 (see above) washing machine, samsung: 5, 6 (see above)
try this
<?php $your_array = array(array("fridges", "samsung", 5, 6), array("fridges", "samsung", 2, 1), array("fridges", "samsung", 3, 4), array("fridges", "lg", 7, 5), array("washing machine", "letto", 5, 6), array("washing machine", "samsung", 5, 6), array("fridges", "samsung", 4, 4)); $arr_temp = array(); foreach($your_array $key=>$arr) { $category = $arr[0]; $sub_category = $arr[1]; $overall_rating = $arr[2]; $extra_rating = $arr[3]; if(isset($arr_temp[$category][$sub_category]['overall'])) { $overall_min = $arr_temp[$category][$sub_category]['overall']['min']; $overall_max = $arr_temp[$category][$sub_category]['overall']['max']; if($overall_rating<$overall_min) { $arr_temp[$category][$sub_category]['overall']['min'] = $overall_rating; } if($overall_rating>$overall_max) { $arr_temp[$category][$sub_category]['overall']['max'] = $overall_rating; } } else { $arr_temp[$category][$sub_category]['overall']['min'] = $overall_rating; $arr_temp[$category][$sub_category]['overall']['max'] = $overall_rating; } if(isset($arr_temp[$category][$sub_category]['extra'])) { $extra_min = $arr_temp[$category][$sub_category]['extra']['min']; $extra_max = $arr_temp[$category][$sub_category]['extra']['max']; if($extra_rating<$extra_min) { $arr_temp[$category][$sub_category]['extra']['min'] = $extra_rating; } if($extra_rating>$extra_max) { $arr_temp[$category][$sub_category]['extra']['max'] = $extra_rating; } } else { $arr_temp[$category][$sub_category]['extra']['min'] = $extra_rating; $arr_temp[$category][$sub_category]['extra']['max'] = $extra_rating; } } foreach($arr_temp $category=>$arr1) { foreach($arr1 $sub_category=>$arr2) { echo $category.",".$sub_category.":".$arr2['overall']['min']."/".$arr2['overall']['max'].",".$arr2['extra']['min']."/".$arr2['extra']['max']; echo "\n"; } } ?>
output :
fridges,samsung:2/5,1/6 fridges,lg:7/7,5/5 washing machine,letto:5/5,6/6 washing machine,samsung:5/5,6/6
Comments
Post a Comment