0

I am getting a REST API response in Wordpress using my ACF fields. I would like to sort the array by two different fields based on a specified order array for each field. I've seen this question, but they are not using custom sort orders, so I'm not sure how to apply the solution to my situation. I've got the sort working for the first order array like this (where product_size is my ACF field):

$sizeOrder = array('Small', 'Medium', 'Large');
usort($data, function ($a, $b) use ($sizeOrder) {
    $pos_a = array_search($a['acf']['product_size'], $sizeOrder);
    $pos_b = array_search($b['acf']['product_size'], $sizeOrder);
    return $pos_a - $pos_b;
});

Now let's say I also want to sort it by another order array for another ACF field called product_color:

$colorOrder = array('White', 'Blue', 'Black');

Is it possible to combine these two sorts into one? I tried just duplicating the code right below and swapping out the order array and ACF field, but then the sort by size doesn't work.

user13286
  • 3,027
  • 9
  • 45
  • 100
  • 1
    Of course you don't get the desired result, if you perform two separate sorting operations. You need to do this both in one go. If two items are of the same size, _then_ you need to compare them regarding their color order, and return the result of that second comparison. – CBroe Aug 25 '21 at 15:07

1 Answers1

0

Ok, so the issue is you're sorting one way then just going in and resorting it to another way eliminating your first sort.

What you need to do is sort in levels so sort by size then by color.

usort should allow you to sort by multiple columns like so:

 usort($data, function ($a, $b) use ($sizeOrder, $colorOrder)