byronyasgur
byronyasgur

Reputation: 4737

Sort an array according to a set of values from another array

I am aware there is another question on SO which is supposed to answer the same thing. My problem is that I don't see what array merge has do do with anything. I don't want to merge the arrays necessarily and I don't understand how that would help ordering them ... also I don't understand where the ordering is coming into it.

If it is relevant could someone please explain in a bit more detail whether the other answer would work for me or not and how

Here is what I have ( the array is quite large so this is a simplification )

Essentially I have something like this

  Array (
    [0] => stdClass Object (
        [term_id] => 72
        [name] => name
        [slug] => slug
        [term_group] => 0
        [term_order] => 1
        [term_taxonomy_id] => 73
        [taxonomy] => gallery_category
        [description] => description
        [parent] => 78
        [count] => 85 )
    [1] => stdClass Object (
        [term_id] => 77
        [name] => name
        [slug] => slug

        etc, etc, etc, there are a lot of objects in the array

Then I have an ordering array like

 Array (
        [0] => 77, 
        [1] => 72,
        etc

So what I want to do is to impose the ordering of the second array on the first one - the ordering array holds the value of the [term_id] from the second array in the corrrect order. In the example above that would mean that I would reverse the order of the first two objects.

Upvotes: 1

Views: 70

Answers (2)

Laizer
Laizer

Reputation: 6140

uksort could do it.

function cmp($a, $b)
{
    $ordering_array=array(0=>77, 1=>72);
    return $ordering_array[$a] - $ordering_array[$b];
}

$a = array() #etc...

uksort($a, "cmp");

Upvotes: 0

Matthew
Matthew

Reputation: 48284

$order_array = [77, 72];

$order_array = array_flip($order_array);

usort($objects, function($a, $b) use ($order_array)
{
  return $order_array[$a->term_id] - $order_array[$b->term_id];
});

This assumes that $order_array has an entry for every term_id.

Upvotes: 3

Related Questions