php - Sorting an array in order defined by other array -
does php have capability sort array of items (a) in order defined array (b)? eg. item comes first in b decides item should come first when sorting a.
$order_to_sort_by = array("gold", "silver", "bronze"); $items_to_sort = array("bronze", "silver", "bronze", "gold", "bronze", "silver"); some_sort_function($items_to_sort, $order_to_sort_by);
result:
gold silver silver bronze bronze bronze
edit: duplicate suggested seems use keys of array determine keys in array should used sorting. unclear, don't think it's duplicate.
you try this
$order_to_sort_by = array("gold", "silver", "bronze"); $items_to_sort = array("bronze", "silver", "bronze", "gold", "bronze", "silver"); $order_to_sort_by_reversed = array_flip($order_to_sort_by); $sortbyarray = function($a, $b) use ($order_to_sort_by_reversed) { return $order_to_sort_by_reversed[$a] - $order_to_sort_by_reversed[$b]; }; usort($items_to_sort, $sortbyarray); var_dump($items_to_sort);
Comments
Post a Comment