I have 2 arrays:
ARR1 = "S, M, L, XL, XXL, 2XL, 3XL, 4XL"
ARR2 = "XL, M, L"
I want to sort ARR2 so that it follows the structure of ARR1. The end result should be: ARR2 = "M, L, XL".
Can't figure out how to do that
Thanks in advance!
Moderator: General Moderators
Code: Select all
/**
* Returns $values array sorted by $index values
*
* @param array $index sort order index
* @param array $values to be sorted
* @return array of $values sorted based on $index
*/
function sortArray($index, $values)
{
$output = array();
foreach ($index as $key)
{
if (in_array($key, $values)) $output[] = $key;
}
return $output;
}
Not sure that I understand your questionBenjamin wrote:What I meant was, what steps would you take to sort them in plain english.
@solid: thanks for the code.Benjamin wrote:I know what order you want them to be in, and I have also written the code to do it.
What I am asking is for you to tell me how you would do this in plain english. If you can't figure out how to sort these in english, or in your head, you certainly won't be able to ever write code to do it.
Code: Select all
echo size_sort('XS,S,M,L,XL,XXL', 'XL,M,S');
function size_sort($original_list, $sortable) {
$original = explode(',', $original_list);
$original = array_flip($original);
$sortable = explode(',', $sortable);
$ret = array();
foreach($sortable as $v) {
if(isset($original[$v]))
$ret[$original[$v]] = $v;
}
ksort($ret);
return implode(',', $ret);
}