1

I have an array of Town objects, and then another object (City) which contains a sort for the first object.

Class City
{
   $id
   $name
   $towns
   $town_id_order
   //etc
}

   Class Town
    {
        $id
        $name
        //etc
    }

So I need to be able to sort the Town based on the City->town_id_order

I'm guessing this is usort but I cannot get it to work with objects as the sort.

This is what I've tried , but returns 'Expects array not string'

function cmp($a, $b)
    {
        if ($a == $this->towns) {
            return 0;
        }
        return ($a < $this->towns) ? -1 : 1;
    }

    $a = $this->getTownsOrder();

    usort($a, "cmp");
2
  • Go ahead and post what you tried. We should be able to help you out with any problems. Commented Jan 30, 2012 at 17:42
  • usort's callback will get two objects as the arguments. Perhaps you could post what you tried with. Commented Jan 30, 2012 at 17:43

2 Answers 2

1

An simple foreach will fit your needs.

$ret = array();
$town_id_order = $city->town_id_order;
foreach ($towns as $town) {
    $ret[array_search($town->id, $town_id_order)] = $town;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This was the route I took , but placed it into a public function within the class then called it from the other method. Thanks.
1
function cmp($a, $b)
{
    if ($a->towns == $b->towns) {
        return 0;
    }
    return ($a->towns < $b->towns) ? -1 : 1;
}

I'm trying to get a feel for your code, but I think the above will work.

2 Comments

Thanks ,still getting 'Warning: usort() expects parameter 1 to be array, string given' with that.
That means that your getTownsOrder() function is returning a string, not an array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.